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

143
Visualizações
Render an authentication protected component after an async authentication

Expected: the async function checks if the user is authenticated, then return true, so that the protected component gets rendered, or false, that redirects the user to the login page.

What actually happens: the getAuth() function returns "Promise ", breaking the code.

  export default function RequireAuth({ children, redirectTo }) {
  const BASE_API_URL = "https://api-backend.test";

  const getAuth = async () => {
    const isAuth = await axios
      .get(BASE_API_URL + "/user_auth.php", {
        withCredentials: true,
      })
      .then((res) => {
        if (res.status === 201) {
          return true;
        }
      })
      .catch((err) => {
        if (err.response.status === 401) {
          return false;
        }
      });

    return isAuth;
  };

  let isAuthenticated = getAuth();
  return isAuthenticated ? children : <Navigate to={redirectTo} />;
}

This is how the "protected" component should be displayed according to the official documentation here.

<Route
  path="/dashboard"
  element={
    <RequireAuth redirectTo="/login">
      <Dashboard />
    </RequireAuth>
  }
/>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You have to do it properly using useEffect, try this

export default function RequireAuth({ children, redirectTo }) {
  const BASE_API_URL = "https://api-backend.test";
  const [isAuthenticated, setAuthenticated] = useState(false);

  useEffect(() => {
    const getAuth = () => {
      const isAuth = axios
        .get(BASE_API_URL + "/user_auth.php", {
          withCredentials: true
        })
        .then((res) => {
          if (res.status === 201) {
            setAuthenticated(true);
          }
        })
        .catch((err) => {
          if (err.response.status === 401) {
            setAuthenticated(false);
          }
        });
    };

    getAuth();
  }, [redirectTo]);

  if (isAuthenticated) {
    return children;
  }
  return <Navigate to={redirectTo} />;
}
about 4 years ago · Juan Pablo Isaza Relatório

0

getAuth is an async function, so it will return a Promise. You have to either await its output or use .then to work with the resolved promise.

Side note, it's usually preferable to either use async/await or .then, but not both.

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