Push into arrays with setState - React Native

162 Views Asked by At

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)
  }
1

There are 1 best solutions below

3
On BEST ANSWER

setState does not update the state immediately -- it gets updated on the next render. Assuming you're actually getting data back from your API, your console.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.

Promise.all(fetches).then(jsonList => {
  this.setState(state => {
     return {
       location: [...state.location, ...jsonList.map(i => i.location)],
       current: [...current, ...jsonList.map(i => i.current)],
       condition: [...state.condition, ...jsonList.map(i => i.condition)],
     }
  },() => {
     console.log(this.state);
  });
})