mirror of
https://github.com/Buriburizaem0n/admin-frontend-domain.git
synced 2026-02-04 12:40:08 +00:00
✨ login page
This commit is contained in:
42
src/hooks/useAuth.tsx
Normal file
42
src/hooks/useAuth.tsx
Normal 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
16
src/hooks/useMainStore.ts
Normal 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),
|
||||
},
|
||||
),
|
||||
)
|
||||
Reference in New Issue
Block a user