Reputation: 3
I am trying to fetch some data from an API and store one of its arrays inside the state and access it inside componentWillMount()
! But when I try to the mentioned states value, I got undefined.
Here is my code:
componentWillMount() {
this._fetchData()
************************************
alert(this.state.openSellOffers)
************************************
}
_fetchData = async () => {
let openSellOffersRes = await fetchOpenSellOffers()
for (let sellOffer of openSellOffersRes.orders) {
let sellObj = {
_id: sellOffer._id,
currencyValue: sellOffer.currencyValue,
unitPrice: sellOffer.unitPrice,
totalPrice: sellOffer.totalPrice,
type: 'sell'
}
this.setState({
openSellOffers: [...this.state.openSellOffers, sellObj]
})
}
}
constructor(props) {
super(props)
this.state = {
IRRBalance: 0,
BTCBalance: 0,
openBuyOffers: [],
openSellOffers: [],
closedBuyOffers: [],
closedSellOffers: []
}
}
As you can see I use alert()
for showing the states value. That is the point which I get undefined instead of the exact value which API responses.
How can I solve it?
Appreciates.
Upvotes: 0
Views: 40
Reputation: 1568
Basically setState() works asynchronously. So you need to wait for a few nanoseconds to get the value. You can do it in 2 ways.
1. Use await
componentWillMount() {
await this._fetchData()
alert(this.state.openSellOffers)
}
_fetchData = async () => {
let openSellOffersRes = await fetchOpenSellOffers()
for (let sellOffer of openSellOffersRes.orders) {
let sellObj = {
_id: sellOffer._id,
currencyValue: sellOffer.currencyValue,
unitPrice: sellOffer.unitPrice,
totalPrice: sellOffer.totalPrice,
type: 'sell'
}
this.setState({
openSellOffers: [...this.state.openSellOffers, sellObj]
})
}
return true;
}
**2. Use SetTimeOut **
componentWillMount() {
this._fetchData()
setTimeout(() => {
alert(this.state.openSellOffers)
}, 100)
}
_fetchData = async () => {
let openSellOffersRes = await fetchOpenSellOffers()
for (let sellOffer of openSellOffersRes.orders) {
let sellObj = {
_id: sellOffer._id,
currencyValue: sellOffer.currencyValue,
unitPrice: sellOffer.unitPrice,
totalPrice: sellOffer.totalPrice,
type: 'sell'
}
this.setState({
openSellOffers: [...this.state.openSellOffers, sellObj]
})
}
}
Upvotes: 1