简体   繁体   中英

Objects not valid as a React child (found: [object Promise])

I have a private route component with renders a route, it returns Uncaught Invariant Violation: Objects are not valid as a React child (found: [object Promise]) when I call a method with async/await . What do I need to change? There is a checkTokenExpirationMiddlewareAdvertiser() that verifies the role of a user and renders the right dashboard. It seems when I async/await for the user the promise doesn't resolve completely.

I have tried removing the async from the function but then i can't get the return value from the function.

const AdvertiserPrivateRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={props => {
      console.log(rest)
      if (!loggedInUser())
        return (
          <Redirect
            to={{ pathname: '/login', state: { from: props.location } }}
          />
        );
      return checkTokenExpirationMiddlewareAdvertiser(
        () => <Component {...props} />, // success component
        () => <AdvertiserError />, // failure component
      );
    }}
  />
);
export const checkTokenExpirationMiddlewareAdvertiser = async (success, fail) => {
  const { user } = await loggedInUser();
  console.log(user)
  if (user) {
    const { token } = user;
    if (jwtDecode(token).exp < Date.now() / 1000) {
      removeUser();
      return fail();
    }
    if (user.role !== 'advertiser') return fail();
    console.log('here');
    return success();
  }
  console.log("here")
  return fail();
};

Your usage of async await in combination with loggedInUser() is inconsistent.

  1. Either remove it from checkTokenExpirationMiddlewareAdvertiser
  2. Or add it to AdvertiserPrivateRoute (see below)

depending on whether loggedInUser() is an asynchronous function

const AdvertiserPrivateRoute = async ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={props => {
      console.log(rest)
      const userLoggedIn = await loggedInUser();
      if (!userLoggedIn)
        return (
          <Redirect
            to={{ pathname: '/login', state: { from: props.location } }}
          />
        );
      return checkTokenExpirationMiddlewareAdvertiser(
        () => <Component {...props} />, // success component
        () => <AdvertiserError />, // failure component
      );
    }}
  />
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM