Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

131
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda