async-library / react-async

🍾 Flexible promise-based React data loader

Home Page:https://docs.react-async.com/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

useAsync always returning undefined

ryanking1809 opened this issue · comments

I'm trying to combine react-async with react-router and am adapting their auth workflow to use react-async (https://reactrouter.com/web/example/auth-workflow). However, my async functions keep returning undefined and I have no idea why.

I have this checkLogin function that returns true when logged in the console.

const checkLogin = async () => {
  let val;
  try {
    val = await localforage.getItem("loggedIn");
  } catch (err) {
    console.error(err);
  }
  console.log("is logged in", val); // returns true
  return val;
};

But with react-async the results are always undefined

const PrivateRoute = ({ children, ...rest }) => {
  const { loggedIn, error, isPending } = useAsync({
    promiseFn: checkLogin
  });
  if (isPending) return "Loading...";
  if (error) return `Something went wrong: ${error.message}`;
  console.log("async login results", loggedIn); // always undefined
  return (
    <Route
      {...rest}
      render={({ location }) =>
        loggedIn ? (
          children
        ) : (
          <Redirect
            to={{
              pathname: "/login",
              state: { from: location }
            }}
          />
        )
      }
    />
  );
};

Is there something I'm missing here. You can test it out via the codesandbox here https://codesandbox.io/s/happy-elion-pjvnn?file=/src/App.js:1156-1734
Just click the login button to view the logs.

There's no loggedIn property on the return value of useAsync. What you're looking for is data.

Oh how incredibly dumb of me 🤦🏼‍♂️ Thanks!