I want to get the user token by react. I use the following code in my login submit form and it’s OK:
in Login.jsx:
const Login = () => {
const { setUserToken } = useContext(AppContext);
const submitForm = async (values) => {
postUserLogin(values)
.then((response) => {
const { token } = response.data;
setUserToken(token);
setApiError({ status: '', error: '' });
navigate('/employer/jobs');
})
.catch((err) => {
setUserToken('');
});
return (<>...</>);
export default Login;
in EmployerJob.jsx:
const EmployerJob = () => {
const { employerJobs, setEmployerJobs, userToken} = useContext(AppContext);
useEffect(() => {
const fetchData = async () => {
const res = await getEmployerJobList(userToken);
if (res.status === 200) {
const { paginator, items: jobs } = res.data;
setPaginatorInfo(paginator);
setEmployerJobs(jobs);
}
}
fetchData();
}, []);
return (
<div className="text-light my-4">
{
<span>Length: {paginatorInfo.count}</span>
}
{
employerJobs.length > 0 ? employerJobs.map((job, index) => (
<p key={index}>{job.salary}</p>
)) : <p>No Job!</p>
}
</div>
);
};
export default EmployerJob;
in appContext.jsx:
import {createContext} from 'react';
export const AppContext = createContext({
userToken:'',
setUserToken:()=>{},
employerJobs:[],
setEmployerJobs:()=>{},
});
and in App.js:
const App= ()=> {
const [userToken, setUserToken] = useImmer('');
const [employerJobs, setEmployerJobs] = useImmer([]);
return(
<AppContext.Provider value={{
userToken,
setUserToken,
employerJobs,
setEmployerJobs,
}}>
<div className='App'>
<Navbar/>
<Routes>
<Route path='/employer/login' element={<Login/>} />
<Route path='/employer/jobs' element={<EmployerJob/>}/>
<Route path="*" element={<NotFound/>}/>
</Routes>
</div>
</AppContext.Provider>
);
}
export default App;
It just work for the first login, but when I refresh the ‘/employer/jobs’ page, the userToken value is empty. I am new to react, I think the userToken should not be changed. Why is it so and how may I solve that?
2
Answers
React state does not persist between page reloads. When a web page is reloaded, all the JavaScript state and data, including React state, are reset.
You can use the browser’s local storage or session storage to store small amounts of data (strings) that will persist between page reloads.
You can store, retrieve and remove data from Local storage this way.
Retrieve token this way.
Remove token
or You can set a cookie
Both these methods have limitations and security considerations.
Refresh token is the best way to implement this.
Your context just gets cleared on page refresh, you will need to persist this state in cookies or local storage (you can do this by yourself using localstorage, but better practice is to use additional libraries to handle a big storages of states).
For it you can use this state managers:
Redux (Quite complicated for the beginners, most used),
Zustand (Lightweight, simple to code)