Fetch Request In Class Component Is Not Returning Data Or Updating State
I have refactored a component to add a fetch request to an AWS database, the data is accessible and a quick mock on codesandbox works. However when used in this context it errors a
Solution 1:
asyncinit() {
...
const mappedUsers = awaitthis.getUsers();
...
You're in async land now.
Solution 2:
There is no defined setState function on the UsersManager class, you will need to create that function
Solution 3:
First, you need to return promise in order to await
it
this.getUsers = () => {
returnfetch(
"DATABASE"
)
.then(res => res.json())
.then(
result => {
this.setState({
isLoaded: true,
users: result.users
});
console.log(result, this.state);
},
error => {
this.setState({
isLoaded: true,
error
});
}
);
};
or use implicit return () => fetch(...)
then,
asyncinit() {
...
const mappedUsers = awaitthis.getUsers();
}
// orinit() {
...
this.getUsers().then((mappedUsers) => { ... });
}
Post a Comment for "Fetch Request In Class Component Is Not Returning Data Or Updating State"