|
| 1 | +"use client"; |
| 2 | +import React, { createContext, useContext, useState, useEffect } from 'react'; |
| 3 | + |
| 4 | +interface UserContextType { |
| 5 | + token: string | null; |
| 6 | + userId: string | null; |
| 7 | + isAuthenticated: boolean; |
| 8 | + login: (token: string, userId: string) => void; |
| 9 | + logout: () => void; |
| 10 | +} |
| 11 | + |
| 12 | +const UserContext = createContext<UserContextType>({ |
| 13 | + token: null, |
| 14 | + userId: null, |
| 15 | + isAuthenticated: false, |
| 16 | + login: () => {}, |
| 17 | + logout: () => {} |
| 18 | +}); |
| 19 | + |
| 20 | +export const useUserContext = () => useContext(UserContext); |
| 21 | + |
| 22 | +export const UserProvider = ({ children }: { children: React.ReactNode }) => { |
| 23 | + const [token, setToken] = useState<string | null>(null); |
| 24 | + const [userId, setUserId] = useState<string | null>(null); |
| 25 | + |
| 26 | + // Initialize from localStorage on client-side |
| 27 | + useEffect(() => { |
| 28 | + const storedToken = localStorage.getItem('token'); |
| 29 | + const storedUserId = localStorage.getItem('userId'); |
| 30 | + |
| 31 | + if (storedToken && storedUserId) { |
| 32 | + setToken(storedToken); |
| 33 | + setUserId(storedUserId); |
| 34 | + } |
| 35 | + }, []); |
| 36 | + |
| 37 | + const login = (newToken: string, newUserId: string) => { |
| 38 | + setToken(newToken); |
| 39 | + setUserId(newUserId); |
| 40 | + // Store in localStorage for persistence |
| 41 | + localStorage.setItem('token', newToken); |
| 42 | + localStorage.setItem('userId', newUserId); |
| 43 | + }; |
| 44 | + |
| 45 | + const logout = () => { |
| 46 | + setToken(null); |
| 47 | + setUserId(null); |
| 48 | + localStorage.removeItem('token'); |
| 49 | + localStorage.removeItem('userId'); |
| 50 | + }; |
| 51 | + |
| 52 | + return ( |
| 53 | + <UserContext.Provider |
| 54 | + value={{ |
| 55 | + token, |
| 56 | + userId, |
| 57 | + isAuthenticated: !!token, |
| 58 | + login, |
| 59 | + logout |
| 60 | + }} |
| 61 | + > |
| 62 | + {children} |
| 63 | + </UserContext.Provider> |
| 64 | + ); |
| 65 | +}; |
0 commit comments