[[Promissevalue]] React

Asked

Viewed 96 times

1

I’m doing a get an api on Nodejs, only the result is coming back within a [[Promisevalue]], how do I access it directly?

With async and await it works, but when for it to authenticate on the route page it does not understand the "true" or "false"

Function that authenticates:

export const isAdmin = () => {

var result = api.get(`/role/listar/${role}`)
console.log(result)
if ("admin" !== "admin") {
    console.log('ola')
    return false

} else {
    console.log("hello")
    return true
}

}

Function that checks whether the user is true or false:

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

Note: I am using React and Xios.

  • "admin" !== " admin" will always return false, no?

  • It was just to set an example.

2 answers

1


api.get(`/role/listar/${role}`)
  .then(results => {
    console.log(result)
  })

or depending on the version of Node

export const isAdmin = async () => {
  var result = await api.get(`/role/listar/${role}`)
  console.log(result)
}
  • But when I go use it to check if it is true or false, it does not understand on account of async and await

  • @Gustavohenrique I don’t know if I understand what you mean, but I’ll change the example considering that your API returns a string with the user’s role

  • Yes, my API returns a JSON with the scroll, so I make a comparison to see if and admin or not.

0

In addition to what Matheus said, it is necessary to return some function value isAdmin().

For example, if your api returns true or false on request, just use async/await, store the value in a variable, for example result and soon after returning this variable return result.

That way you can use her isAdmin() in a if for example, because when it is executed, it will return a value true or false.

Browser other questions tagged

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