-
Notifications
You must be signed in to change notification settings - Fork 19
/
state.ts
51 lines (42 loc) · 1.28 KB
/
state.ts
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
42
43
44
45
46
47
48
49
50
51
import { useMemo } from 'react';
import { atom, useAtom, useAtomValue } from 'jotai';
import { store } from '@/app/providers/Jotai';
type AuthState = {
userId: string;
token: string | undefined;
};
const initialValue: AuthState = {
userId: '',
token: undefined,
};
const userIdAtom = atom(initialValue.userId);
const baseTokenAtom = atom(localStorage.getItem('token') ?? initialValue.token);
const tokenAtom = atom(
(get) => get(baseTokenAtom),
(_, set, value: AuthState['token']) => {
set(baseTokenAtom, value);
value === undefined
? window.localStorage.removeItem('token')
: window.localStorage.setItem('token', value);
},
);
const isLoggedInAtom = atom(
(get) => get(userIdAtom) !== initialValue.userId && get(tokenAtom) !== initialValue.token,
);
export const useAuthState = () => {
const [userId, setUserId] = useAtom(userIdAtom);
const [token, setToken] = useAtom(tokenAtom);
const isLoggedIn = useAtomValue(isLoggedInAtom);
return useMemo(
() =>
[
{ userId, token, isLoggedIn },
({ userId, token }: AuthState = initialValue) => {
setUserId(userId);
setToken(token);
},
] as const,
[userId, token, isLoggedIn, setUserId, setToken],
);
};
export const getToken = () => store.get(tokenAtom);