update: Set zustand storage.

mack-mac
mackt 8 months ago
parent 6d7172515e
commit a3def0adc4

@ -1,6 +1,7 @@
import { produce } from 'immer';
import { setCookie } from 'nookies';
import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import { apiGetMyUserInfo, apiUserLogin } from '@/services';
@ -19,54 +20,63 @@ interface UserState {
getUserInfo: () => Promise<boolean>;
}
// 创建状态存储
const useUserStore = create<UserState>((set) => {
const getUserInfo = async () => {
const result = await apiGetMyUserInfo();
if (result.code === 200) await set(produce((state) => void (state.userInfo = result.data)));
return result.code === 200;
};
const useUserStore = create<UserState>()(
devtools(
persist(
(set) => {
const getUserInfo = async () => {
const result = await apiGetMyUserInfo();
if (result.code === 200) await set(produce((state) => void (state.userInfo = result.data)));
return result.code === 200;
};
return {
userInfo: {
avatar: '',
badgeList: [0],
birthDay: '',
commentReplyCount: 0,
contributorRole: '',
fansCount: '',
followCount: '',
haveNewMessage: false,
id: '',
ipLocation: '',
journalCount: 0,
mobile: '',
nickName: '',
relation: 0,
sex: 0,
signature: '',
songCount: 0,
thumbUpCount: 0,
},
// 展示登录框
showLogin: false,
// 调用出登录框
setShowLogin: (value) => set({ showLogin: value }),
// 更新用户信息
setUserInfo: (userInfo) => set({ userInfo }),
// 获取用户信息
getUserInfo,
// 用户登录
userLogin: async (params) => {
const result = await apiUserLogin(params);
if (result.code !== 200) return false;
await setCookie(null, 'token', result.data, {
maxAge: 7 * 24 * 60 * 60,
path: '/',
});
return await getUserInfo();
},
};
});
return {
userInfo: {
avatar: '',
badgeList: [0],
birthDay: '',
commentReplyCount: 0,
contributorRole: '',
fansCount: '',
followCount: '',
haveNewMessage: false,
id: '',
ipLocation: '',
journalCount: 0,
mobile: '',
nickName: '',
relation: 0,
sex: 0,
signature: '',
songCount: 0,
thumbUpCount: 0,
},
// 展示登录框
showLogin: false,
// 调用出登录框
setShowLogin: (value) => set({ showLogin: value }),
// 更新用户信息
setUserInfo: (userInfo) => set({ userInfo }),
// 获取用户信息
getUserInfo,
// 用户登录
userLogin: async (params) => {
const result = await apiUserLogin(params);
if (result.code !== 200) return false;
await setCookie(null, 'token', result.data, {
maxAge: 7 * 24 * 60 * 60,
path: '/',
});
return await getUserInfo();
},
};
},
{
name: 'user',
getStorage: () => localStorage,
},
),
),
);
export default useUserStore;

Loading…
Cancel
Save