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

126
Views
render Component after updating the state

what u see below is my App.js Component

export default function App() {
  const [userData, setUserData] = useState(null);

  useEffect(() => {
    try {
      const jwt = localStorage.getItem("token");
      const user = jwtDecode(jwt);
    console.log("user", user);
      setUserData(user);
      console.log("emp1", userData);
    } catch (ex) {}
  });

  console.log("emp2", userData);
  render(
    <BrowserRouter>
      <ToastContainer
        rtl
        position="top-left"
        style={{ width: 520, fontSize: 15 }}
      />
      <div className="App">
        <Navbar userData={userData} />
      </div>
    </BrowserRouter>,
    document.getElementById("root")
  );
}

as u see on the top i defined null value for my state and i want to update the state with the object that i get from the decoded token but i dont know why state does not update?

NOTE: i want to send the state as a props to the Navber.js Component

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You need to set dependency array in useEfect:

useEffect(() => {
    try {
      const jwt = localStorage.getItem("token");
      const user = jwt.decode(jwt);
      setUserData(user);
      console.log("emp1", userData);
    } catch (ex) {}
  }, []);

[] in useEffect means:

If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run. This isn’t handled as a special case — it follows directly from how the dependencies array always works.

UPDATE:

You need to use jwt.decode(token) not jwtDecode:

 useEffect(() => {
    try {
      const jwt = localStorage.getItem("token");
      const user = jwt.decode(jwt);
      setUserData(user);
      console.log("emp1", userData);
    } catch (ex) {}
  }, []);

I've created an example how it is possible to send data to functional component at Stackblitz.

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!