Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
The state variable declared in context is not persisting its value

I am using a context state variable to store my token value when user signs in. And using that token through out my application. When I log in, the token is console logged on the login page. But it gives empty value on other pages even though I am using the context in all the files.

AuthContext.js

export const AuthContext = createContext();

export const AuthProvider = (props) => {
  const [authToken, setAuthToken] = useState("");
  const [authProtected, setAuthprotected] = useState(true);

  return (
    <AuthContext.Provider
      value={{
        token: [authToken, setAuthToken],
        authProtect: [authProtected, setAuthprotected],
      }}
    >
      {props.children}
    </AuthContext.Provider>
  );
};

Login.js

const userAuth = (e) => {
    e.preventDefault();
    Axios.post(authApi, loginInfo).then((res) => {
      setJwtToken(res.data.idToken.jwtToken);
    });
  };
  console.log(jwtToken);

After log in, I use this in one of my pages and it logs an empty value

const { token } = useContext(AuthContext);
const [jwtToken, setJwtToken] = token;

console.log(jwtToken);
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

When the page reloads, the context is recreated. You need to use a useEffect within the context to refetch the information from the backend and save the token in case you are saving to some cookie or localstorange.

Put the token in the cookie and when it switches pages, retrieve the cookie by useEffect to save again in context

Note: when you switch pages, everything in the context is recreated, so when the page goes to get something from the context, it will be empty

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!