feat: introduce authentication context

This commit is contained in:
Ali BARIN
2022-03-08 19:50:51 +01:00
committed by Ömer Faruk Aydın
parent 030d886cf7
commit 5d1c4b81e7
8 changed files with 103 additions and 26 deletions

View File

@@ -0,0 +1,39 @@
import * as React from 'react';
import { getItem, setItem } from 'helpers/storage';
export type AuthenticationContextParams = {
token: string | null;
updateToken: (token: string) => void;
};
export const AuthenticationContext = React.createContext<AuthenticationContextParams>({
token: null,
updateToken: () => void 0,
});
type AuthenticationProviderProps = {
children: React.ReactNode;
};
export const AuthenticationProvider = (props: AuthenticationProviderProps): React.ReactElement => {
const { children } = props;
const [token, setToken] = React.useState(() => getItem('token'));
const value = React.useMemo(() => {
return {
token,
updateToken: (newToken: string) => {
setToken(newToken);
setItem('token', newToken);
},
};
}, [token]);
return (
<AuthenticationContext.Provider
value={value}
>
{children}
</AuthenticationContext.Provider>
);
};