-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore.ts
64 lines (52 loc) · 1.49 KB
/
store.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
52
53
54
55
56
57
58
59
60
61
62
63
64
import AsyncStorage from '@react-native-async-storage/async-storage';
import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import { User } from './models/User';
import { Backend } from './backend';
interface AppState
{
currentUser?: User;
authToken?: string;
setCurrentUser(currentUser: User, authToken: string): void;
clearCurrentUser(): void;
updateUserInfo(info: Partial<User>): void;
refreshUserInfo(): Promise<void>;
signOut(fromAll: boolean): Promise<void>;
}
export const useAppState = create(
persist<AppState>(
(set, get) => ({
setCurrentUser(currentUser, authToken) {
set({ currentUser, authToken });
},
clearCurrentUser() {
set({ currentUser: undefined, authToken: undefined });
},
updateUserInfo(info) {
set({
currentUser: { ...get().currentUser, ...info } as User,
})
},
async refreshUserInfo() {
const backend = new Backend(useAppState.getState().authToken);
const result = await backend.request<any>('GET', '/profile/self');
if (result?.profile)
{
console.log(result);
get().updateUserInfo(result.profile);
}
},
async signOut(fromAll) {
const backend = new Backend(useAppState.getState().authToken);
await backend.request('POST', '/auth/logout', {
json: { fromAll }
});
set({ currentUser: undefined, authToken: undefined });
}
}),
{
name: 'networker-persisted',
storage: createJSONStorage(() => AsyncStorage)
}
)
);