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

356
Visualizações
Return from a funtion only when API returns a success response from backend in React

I need a help on regarding private routing in react-router-6.Actually, I want to return a component only when the backend API returns success response. please see the following code snipet,

export default function PrivateOutlet() {
const dispatch = useDispatch();

useEffect(() => {
    dispatch(getCurrentUser())
    .then((res) => {
        localStorage.setItem('id', res.id);
    })
    .catch(error => console.log(error) );
}, [);
return   (localStorage.getItem('id') !== "undefined") ? <Outlet /> : <Navigate to="/login" />
};

Here, the problem is , before returning success response from the getCurrentUser() API this function PrivateOutlet returns value. can you please help on this?

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

The localStorage seems completely extraneous/superfluous if what you really want is to use the getCurrentUser action to get an id. Use a local state id that doesn't match the authenticated or unauthenticated id value. Wait until the id state is populated to render the Outlet or redirect.

Example:

export default function PrivateOutlet() {
  const [id, setId] = React.useState();
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(getCurrentUser())
      .then((res) => {
        setId(res.id); // valid id or null
      })
      .catch(error => {
        console.log(error);
        setId(null);
      );
  }, []);

  if (id === undefined) return null; // or loading indicator/spinner/etc

  return (id)
    ? <Outlet />
    : <Navigate to="/login" replace />
};

If wanting to continue using localStorage, then use a local "loading" state and conditionally render null or some loading indicator until the current user id is fetched. Also, I'm not sure if it was a typo, but you very likely meant to compare the value from localStorage against undefined and not the string literal "undefined". This still works because the loading state update triggers a rerender and the component can read the id value just set in localStorage.

Example:

export default function PrivateOutlet() {
  const [isLoaded, setIsLoaded] = React.useState(false);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(getCurrentUser())
      .then((res) => {
        localStorage.setItem('id', res.id);
      })
      .catch(error => {
        console.log(error);
        localStorage.removeItem('id');
      )
      .finally(() => setIsLoaded(true));
  }, []);

  if (!isLoaded) return null; // or loading indicator/spinner/etc

  return (localStorage.getItem('id') !== undefined)
    ? <Outlet />
    : <Navigate to="/login" replace />
};
about 4 years ago · Santiago Gelvez 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