I have an API that return my expected results in a react project.
I wrote this function to call API and get the results:
async function getUsers() {
const token = store.getState().token;
const data = { token };
await MyApi.getUsers(data)
.then((result) => {
console.log(result);
return result;
})
.catch((error) => {
console.log(error);
return null;
});
}
const userList = getUsers();
When I console.log the result
in the then
section of the function, it printed the expected list of users (that is a json array).
But when I console.log the userList
it is a promise
like bellow image:
that means the returned value of getUsers
function is a Promise
.
1- How can I get the results from this promise?
2- why the PromiseResult
is undefined
while the result
in then
section is a json array?
** these codes are not in the react component
the expected result
is:
[
{
id: 1,
name: "user1",
role: "student"
},
{
id: 2,
name: "user2",
role: "student"
},
{
id: 3,
name: "user3",
role: "student"
},
]
and I want to use userList
array to create user card
:
<div>
{userList ? (
userList.map((user) =>
{
<Card>
<h1> user.name </h1>
</Card>
}
):
(<h1>user list is empty </h1>)
}