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

117
Visualizações
React Context Hook state not changing

I am Creating a simple MERN Authentication, my backend works completely fine, and have tested it with postman, it gives boolean responses when checking for if the user is logged in.

Below is the Router to check the logged-in user, and sending the boolean values to the frontend.

router.get("/loggedIn", (req, res) => {
  try {
    const token = req.cookies.token;
    if (!token) return res.json(false);

    jwt.verify(token, process.env.JWT_SECRET);
    res.send(true);
  } catch (err) {
    res.json(false);
  }
});

In React, I am using Context Hook, to get that response using Axios.

import React, { useState, useEffect, createContext } from "react";
import Axios from "axios";

const AuthContext = createContext();

function AuthContextProvider(props) {
  const [loggedIn, setLoggedIn] = useState(undefined);

  const getLoggedIn = async () => {
    await Axios.get("http://localhost:5000/auth/loggedIn")
      .then((res) => setLoggedIn(res.data))
      .catch((err) => console.log(err));
  };

  useEffect(() => {
    getLoggedIn();
  }, []);

  return (
    <AuthContext.Provider value={{ loggedIn, getLoggedIn }}>
      {props.children}
    </AuthContext.Provider>
  );
}

export default AuthContext;
export { AuthContextProvider };

I'm using the loggedIn to conditionally render some components, but the value of it or the state always stays false, if I change the state from dev tools conditional rendering works fine.

AuthContext implementation,

const { loggedIn } = useContext(AuthContext);

 {loggedIn === false && (
                <Link className="nav-link" to="/login">
                  <FaUser />
                </Link>
            )}

            {loggedIn === true && (
                <Link className="nav-link" to="/logout">
                  <Button variant="outline-dark">Logout</Button>
                </Link>
            )}

As you can see, I just want to conditionally render a component, but it always returns false

I am new to the ContextHook.

about 4 years ago · Juan Pablo Isaza
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