Reputation: 131
So I want to set my state for my bookings to be my result.data, the request is working and I can console.log(result.data). However when I try to set the state and then check that state, it's empty. What is going on? Does it have something to do with my params I'm passing to axios?
My initial state looks like: this.state = {bookingArrayByDate: []}
Tried setting the state outside "then" but that didn't work either
componentDidMount() {
let today = moment(new Date())
let dateToSend = today.format('YYYY-MM-DD')
axios
.get(
`http://localhost:8888/booking-backend/fetch-reservation.php/`,
{ params: { res_date: dateToSend } }
)
.then((result: any) => {
console.log(result.data)
this.setState({
bookingArrayByDate: result.data
})
})
console.log('this is outside', this.state.bookingArrayByDate)
}
The array at the bottom will be empty when i console log it.
Upvotes: 0
Views: 1866
Reputation: 15688
Your code is fine. What you are experiencing is the standard asynchronous behavior ofthis.setState()
. When you console.log()
your state
, there is no guarantee that it was updated in the time between your setState()
and the console.log()
execution.
In fact, its almost 100% unlikely that it was changed within that time, because React actually batches setState()
requests by putting them in a queue until the entire event is completed. In your case, the setState()
wouldn't actually occur until after the componentDidMount()
logic finishes.
What you can do is pass a call-back as the 2nd argument to this.setState()
, that call-back is executed directly after the state
has finished updating, thus ensuring you are printing the updated state
.
componentDidMount() {
let today = moment(new Date())
let dateToSend = today.format('YYYY-MM-DD')
axios
.get(
`http://localhost:8888/booking-backend/fetch-reservation.php/`,
{ params: { res_date: dateToSend } }
)
.then((result: any) => {
this.setState({
bookingArrayByDate: result.data
}, () => console.log(this.state.bookingArrayByDate)) <-- you can swap this whatever function you need.
})
}
Upvotes: 4