How to return Boolean from a Promise<Boolean> in React.js?

Asked

Viewed 14 times

-2

I have this checkRouteAuthentication function()

async function checkRouteAuthentication() {
    const body = {
        token: localStorage.getItem("token")
    }

    const resp = await hostApi.post("empresa/isAuthenticated", body);
    localStorage.setItem("isAuth", resp.data);

    return resp.data;
}

And I want to do, for example, the following: If my function returns true I re-address my component, if false, I am redirected to login

const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route
        {...rest}
        render={props =>
            checkRouteAuthentication() ? (
                <Component {...props} />
            ) : (
                <Redirect to={{ pathname: "/login", state: { from: props.location } }} />
            )
        }
    />
);

And it’s always falling in the True case even though Resp.data is false, which I should do for that code to work?

Function signature when mouse over:

function checkRouteAuthentication(): Promise<boolean>
  • If resp.data is an object, will always be true, because objects are values Truthy.

  • Resp.data is a Boolean. The Resp itself is an object but when it puts . data it returns Boolean

  • You need to use the await or perform the condition within the then. An object Promise will always be seen as value Truthy by the ternary operator, so that the second term (of the ternary) will always be the evaluated.

  • Moreover, it is likely that resp be a string, no? "false" (which is a string) is Truthy.

  • I rephrased the question to equalize my current situation

  • Resp is an object and Resp.data is a Boolean for sure, I checked with typeof

  • Really missed the await. The way you’re calling, you’ll return a Promise Object, soon will be Truthy.

  • Where do I put this await?

Show 3 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.