I'm trying to get data from MongoDb, but setState not updating bookInstances
How can I use setState to update bookInstances? and each array is basically like {"id": ...}
export default class BookInstances extends Component {
constructor(props) {
super(props)
this.BookInstance = this.BookInstance.bind(this);
this.BookInstances = this.BookInstances.bind(this);
this.state = {
bookInstances: []
}
}
componentDidUpdate() {
axios.get('http://localhost:3001/catalog/bookinstances')
.then(res => {
this.setState({ bookInstances: res.data });
})
}
BookInstance(props) {
return <li>{props.bookInstance}</li>
}
BookInstances() {
const bookInstances = this.state.bookInstances;
if (bookInstances) {
return bookInstances.map(bookInstance => {
return <this.BookInstance key={bookInstance} bookInstance={bookInstance.id} />
})
}
}
render() {
return (
<div>
<h1>Book Instance List</h1>
<ul><this.BookInstances /></ul>
</div>
)
}
}
Appreciate any assistance ?
Not sure why you'd use a class component nowadays.. Nonetheless, you're setting state in the wrong lifecycle method.
You'll need to fetch within componentDidMount()
componentDidMount() {
axios.get('http://localhost:3001/catalog/bookinstances')
.then(res => {
this.setState({ bookInstances: res.data });
})
}
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.