-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.datais an object, will always betrue, because objects are values Truthy.– Cmte Cardeal
Resp.data is a Boolean. The Resp itself is an object but when it puts . data it returns Boolean
– Michael Jonathan
You need to use the
awaitor perform the condition within thethen. An objectPromisewill always be seen as value Truthy by the ternary operator, so that the second term (of the ternary) will always be the evaluated.– Luiz Felipe
Moreover, it is likely that
respbe a string, no?"false"(which is a string) is Truthy.– Luiz Felipe
I rephrased the question to equalize my current situation
– Michael Jonathan
Resp is an object and Resp.data is a Boolean for sure, I checked with typeof
– Michael Jonathan
Really missed the
await. The way you’re calling, you’ll return a Promise Object, soon will be Truthy.– Cmte Cardeal
Where do I put this await?
– Michael Jonathan