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

96
Visualizações
Returning a value which is currently in promised state

So this is more of a javascript question than a reactjs question. I am creating a protected route in reactjs. In this, I am fetching the '/checkauth' get request to check the authentication and it correctly returns the response to me. However the problem is that since it is an async function, it takes time to return that value and thus my return statement is executed earlier. This is the code I am having problem with.

const [auth, setAuth] = useState();

const checkAuthentication = async ()=>{
    const res = await fetch('/checkauth', {
        method : "GET",
        credentials: "include", 
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        }
    });
    const data = await res.json();
    return res.status===200 ? (data.isAuthenticated) : (false) ;
}

useEffect(async ()=>{
    const data = await checkAuthentication();
    setAuth(data)
}, []);

return auth ? <Outlet /> : <Navigate to='/signin' />;

Here the auth is always undefined and thus it always navigates to signing.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Use three states.

const [auth, setAuth] = useState("loading");

...

setAuth(data ? "auth" : "not-auth");

...

if (auth === "loading")
    return <Loading />
else if (auth === "not-auth")
    return <Navigate to='/signin' />
else 
    return <Outlet />
about 4 years ago · Juan Pablo Isaza Relatório

0

You can return a loading spinner while fetching the data, and when the request completes the state will be updated and the <Outlet /> component will be rendered.

By the way: When you are passing an async function to the useEffect hook, it returns a promise and useEffect doesn't expect the callback function to return Promise, rather it expects that the callback returns nothing (undefined) or a function (typically a cleanup function).

Try this:

useEffect(() => {
  // declare the async data fetching function
  const fetchData = async () => {
    // get the data from the api
    const data = await fetch('https://yourapi.com');
    // convert the data to json
    const json = await response.json();

    // set state with the result
    setData(json);
  }

  // call the function
  fetchData()
    // make sure to catch any error
    .catch(console.error);;
}, [])

  • More info:

React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing

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