Home > database >  Return from a funtion only when API returns a success response from backend in React
Return from a funtion only when API returns a success response from backend in React

Time:04-11

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?

CodePudding user response:

The localStorage seems completely extraneous/superfluous if what you really want is to use the getCurrentUser action to get an id. 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".

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/spinnet/etc

  return (localStorage.getItem('id') !== undefined)
    ? <Outlet />
    : <Navigate to="/login" replace />
};
  • Related