UserContext
This commit is contained in:
13
src/utils/users/UseUser.ts
Normal file
13
src/utils/users/UseUser.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
|
||||
import {UserContext} from "./UserContext.ts";
|
||||
import {useContext} from "react";
|
||||
|
||||
|
||||
|
||||
export function useUser() {
|
||||
const context = useContext(UserContext);
|
||||
if (!context) {
|
||||
throw new Error('useUser must be used within a UserProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
10
src/utils/users/UserContext.ts
Normal file
10
src/utils/users/UserContext.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import {Account} from "../../types/users.ts";
|
||||
import {createContext} from "react";
|
||||
|
||||
export type UserContextType = {
|
||||
user: Account | undefined;
|
||||
login: (userData: Account) => void;
|
||||
logout: () => void;
|
||||
};
|
||||
|
||||
export const UserContext = createContext<UserContextType | undefined>(undefined);
|
||||
35
src/utils/users/UserProvider.tsx
Normal file
35
src/utils/users/UserProvider.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
import React, {ReactNode, useEffect, useState} from 'react';
|
||||
import {Account} from '../../types/users.ts';
|
||||
import {UserContext} from "./UserContext.ts";
|
||||
|
||||
|
||||
export function UserProvider({ children }: { children: ReactNode }) {
|
||||
const [user, setUser] = useState<Account | undefined>(() => {
|
||||
const storedUser = localStorage.getItem('user');
|
||||
return storedUser ? JSON.parse(storedUser) : undefined;
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
localStorage.setItem('user', JSON.stringify(user));
|
||||
document.cookie = `user=${encodeURIComponent(JSON.stringify(user))}; path=/;`;
|
||||
} else {
|
||||
localStorage.removeItem('user');
|
||||
document.cookie = 'user=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC;';
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
const login = (userData: Account) => {
|
||||
setUser(userData);
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
setUser(undefined);
|
||||
};
|
||||
|
||||
return (
|
||||
<UserContext.Provider value={{ user, login, logout }}>
|
||||
{children}
|
||||
</UserContext.Provider>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user