Hello my friends , i have an app , when i login he know the currentUser but when i reload a page he doesn't know the user authentificated , how can i preserves the user data in currentUser this is the code of contextProvider :
/* eslint-disable no-unused-vars */
import { createContext , useContext , useState } from "react";
const StateContext = createContext({
currentUser: {},
userToken: null,
setCurrentUser: () => {},
setUserToken: () => {},
changeRequests: () => {},
setChangeRequests: () => {},
toast: {
message: null,
show: false,
},
currentPage: 1,
setCurrentPage : () => {},
totalPages: 3,
setTotalPages: () => {},
})
// eslint-disable-next-line react/prop-types
export const ContextProvider = ({children}) => {
const [currentUser, setCurrentUser] = useState({});
const [userToken,_setUserToken] = useState(localStorage.getItem('TOKEN') || '');
const [changeRequests, setChangeRequests] = useState([]);
const [toast, setToast] = useState({message: '', show: false});
const [currentPage, setCurrentPage] = useState(1);
const [totalPages, setTotalPages] = useState(1);
const setUserToken = (token) => {
if (token) {
localStorage.setItem('TOKEN', token)
} else {
localStorage.removeItem('TOKEN')
}
_setUserToken(token);
}
const showToast = (message) => {
setToast({ message, show: true })
setTimeout(() => {
setToast({message: '', show: false})
}, 5000)
}
return (
<StateContext.Provider value= {{
currentUser,
setCurrentUser,
userToken,
setUserToken,
changeRequests,
setChangeRequests,
toast,
showToast,
currentPage,
setCurrentPage,
totalPages,
setTotalPages,
}}>
{children}
</StateContext.Provider>
)
};
// eslint-disable-next-line react-refresh/only-export-components, react-hooks/rules-of-hooks
export const useStateContext = () => useContext(StateContext);