I am trying to make a fetch from a local server in Node, but my problem is that when I call the render function of the component the array users from the state seems to be empty and therefore does not render the users on the screen as I would like, the weird thing is that the console.log(users)
I have inside the fetch does bring me the data, but when I do it on the render does not bring me anything:
this is the code so far:
import React, { PureComponent } from "react";
import Nav from "./Nav";
import { IState, IProps } from "./Interfaces";
class Home extends PureComponent<IProps, IState> {
constructor(props: IProps) {
super(props);
this.state = {
users: [],
books: []
};
}
getUsers = async () => {
const response = await fetch(`http://localhost:5000/users`, {
headers: {
"Content-Type": "application/json"
}
});
const users = await response.json();
for (let user of users) {
this.state.users.push(user);
}
console.log(this.state.users);
};
getBooks = async (id: number) => {
const token =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlciI6Implc3VzIiwiaXNBZG1pbiI6dHJ1ZSwiaWF0IjoxNTc2NjgzNTkwfQ.1FWmtj-fCsqSza_pwfewIpp3zQ50BxDagRTvrh5x3cU";
const response = await fetch(`http://localhost:5000/bookUser/${id}/books`, {
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json"
}
});
const books = await response.json();
this.setState({ books });
};
onUserSelection = (id: number) => this.getBooks(id);
componentDidlMount() {
this.getUsers();
}
render() {
const { users } = this.state;
console.log(this.state.users);
return (
<div>
<Nav username={this.props.username} />
<h1>Hello {this.props.username}</h1>
<table>
<tbody>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
{users.map(u => (
<tr
key={u.user_id}
onClick={() => this.onUserSelection(u.user_id)}
>
<td>{u.user_id}</td>
{console.log(u.user_id)}
<td>{u.username}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
}
export default Home;
As previously mentioned in Sameer's comment, you want to avoid using push when setting state. Doing this will not trigger a re-render.
Instead of the this.state.users.push(user)
you're doing, replace that (and the console.log following it) with this:
this.setState(prevState => ({
users: [...prevState.users, user]
}, console.log("updated users", this.state.users)));
A few things different here.
The first argument in setState takes in a function. There is an argument exposed in that function which is your previous state (prevState). Using the spread operator you can create a new array with the old users and all the new ones.
Secondly, due to the asynchronous nature of setState, you can't expect to run a console.log() right after a setState function. Instead, you can pass a callback function (console.log in this instance) as the second argument to setState & it will be fired when completed.
Use setState
to populate users in state
this.setState({
users: users
})
and in render before map, do this
{
users.length>0 &&
users.map(u => ( <tr key={u.user_id} onClick={() => this.onUserSelection(u.user_id)} > <td>{u.user_id}</td> {console.log(u.user_id)} <td>{u.username}</td> </tr> ))
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.