Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

350
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!