Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

351
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda