skip to Main Content

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


  1. 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.

    // Storing data in local storage
    const dataToStore = { key: 'value', foo: 'bar' };
    localStorage.setItem('myData', JSON.stringify(dataToStore));

    Retrieve token this way.

    // Retrieving data from local storage
    const storedData = localStorage.getItem('myData');
    const parsedData = JSON.parse(storedData);

    Remove token

    // Removing data from local storage
    localStorage.removeItem('myData');

    or You can set a cookie

    const expirationDate = new Date();
    expirationDate.setDate(expirationDate.getDate() + 7); // Expires in 7 days
    
    document.cookie = `myCookie=myValue; expires=${expirationDate.toUTCString()}`;

    Both these methods have limitations and security considerations.

    Refresh token is the best way to implement this.

    Login or Signup to reply.
  2. 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)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search