login page

This commit is contained in:
naiba
2024-11-02 22:34:43 +08:00
parent d945ca97c1
commit 017e6cfdcf
32 changed files with 2236 additions and 170 deletions

42
src/hooks/useAuth.tsx Normal file
View File

@@ -0,0 +1,42 @@
import { createContext, useContext, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { useMainStore } from "./useMainStore";
import { AuthContextProps, User } from "@/types";
const AuthContext = createContext<AuthContextProps>({
profile: undefined,
login: () => { },
logout: () => { },
});
export const AuthProvider = ({ children }: {
children: React.ReactNode;
}) => {
const profile = useMainStore(store => store.profile)
const setProfile = useMainStore(store => store.setProfile)
const navigate = useNavigate();
const login = async (profile: User | undefined) => {
setProfile(profile);
navigate("/dashboard");
};
const logout = () => {
setProfile(undefined);
navigate("/dashboard/login", { replace: true });
};
const value = useMemo(
() => ({
profile,
login,
logout,
}),
[profile]
);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};
export const useAuth = () => {
return useContext(AuthContext);
};

16
src/hooks/useMainStore.ts Normal file
View File

@@ -0,0 +1,16 @@
import { MainStore, User } from '@/types'
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
export const useMainStore = create<MainStore, [['zustand/persist', MainStore]]>(
persist(
(set, get) => ({
profile: get()?.profile,
setProfile: (profile: User | undefined) => set({ profile }),
}),
{
name: 'mainStore',
storage: createJSONStorage(() => localStorage),
},
),
)