-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwithAuthSyncEvents.tsx
41 lines (33 loc) · 1.05 KB
/
withAuthSyncEvents.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { useEffect } from 'react';
import Router from 'next/router';
import omit from 'lodash/omit';
import globalEvents from 'config/globalEvents.json';
import { TNextPage } from 'lib/apollo/types';
const { SIGN_IN_EVENT, SIGN_OUT_EVENT } = globalEvents;
const withAuthSyncEvents = (Page: TNextPage): TNextPage => {
const syncAuthHandler = (event: StorageEvent) => {
switch (event.key) {
case SIGN_OUT_EVENT:
case SIGN_IN_EVENT:
Router.reload();
break;
default:
break;
}
};
const WithAuthSyncEvents: TNextPage = ({ ...pageProps }) => {
useEffect(() => {
window.addEventListener('storage', syncAuthHandler);
return () => {
window.removeEventListener('storage', syncAuthHandler);
};
}, []);
return <Page {...pageProps} />;
};
WithAuthSyncEvents.getInitialProps = context => {
const ctx = omit(context, ['req', 'res']);
return Page.getInitialProps ? Page.getInitialProps(context) : ctx;
};
return WithAuthSyncEvents;
};
export default withAuthSyncEvents;