Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda