Skip to content

Commit

Permalink
feat: Added hook to handle native back events in a SPA (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
mircostraessle authored and dwirz committed Jan 10, 2020
1 parent 5267aa9 commit bf5e6a5
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,20 @@ const [updateAvailable, installUpdate] = useServiceWorker('service-worker.js');
onUpdate={installUpdate}
/>
)}
```

## useNativeBack hook

This React hook allows the handling of a native back event, e.g. from a browser or mobile phone OS, in a single page web app.

The following example demonstrates the usage with an XState-Statemachine. The statemachine transitions will be viewed as route changes and a native back event will be handled by an action sent to the statemachine.

```tsx
import { useNativeBack } from '@smartive/react-pwa-toolbox';
import { useMachine } from '@xstate/react';

const [current, send, service] = useMachine(StateMachine);

const routeChanged = useNativeBack(() => send('BACK'));
service.onTransition((current) => routeChanged(current.value));
```
1 change: 1 addition & 0 deletions src/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './use-service-worker';
export * from './use-native-back';
16 changes: 16 additions & 0 deletions src/hooks/use-native-back.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { useEffect } from 'react';

export const useNativeBack = (backAction: () => void) => {
useEffect(() => {
const onPop = (event: Event) => {
event.preventDefault();
backAction();
};

addEventListener('popstate', onPop);

return () => removeEventListener('popstate', onPop);
}, []);

return (route: Parameters<History['pushState']>[0]) => window.history.pushState(route, document.title);
};

0 comments on commit bf5e6a5

Please sign in to comment.