i'm new to React Native and i was working on a project using api from different url's. When i use the fetch to the url's, i want so set my state with setState but when i try it, the console.warn shows my arrays empy. What is the problem in my code? I appreciate any feedback :)
constructor() {
super();
this.state = {
location: [],
current: [],
condition: [],
cities: ["london", "paris", "hongkong", "buenos_aires"]
}
}
componentDidMount() {
let fetches = []
this.state.cities.forEach(
city => {
let resp = fetch('http://api.weatherapi.com/v1/current.json?key=10eb2b8701194b128b2122427211005&q=' + city + '&aqi=no').then(res => res.json());
fetches.push(resp)
}
)
Promise.all(fetches).then(jsonList => {
jsonList.forEach(
json => {
this.setState(state => {
const location = state.location.concat(json.location)
const current = state.current.concat(json.current)
const condition = state.condition.concat(json.condition)
return {
location,
current,
condition,
}
})
})
}).catch(function (error) {
console.error(error)
})
console.warn(this.state)
}
setState
does not update the state immediately -- it gets updated on the next render. Assuming you're actually getting data back from your API, yourconsole.warn
is showing the state from the current render.You can use the callback function (second argument of
setState
) to see the value after it's been set.You can also make all of the updates in one shot by using array spreading.