2

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)
  }
User 12345
  • 23
  • 4

1 Answers1

1

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);
  });
})
jnpdx
  • 45,847
  • 6
  • 64
  • 94
  • Thanks for the answer, it was exactly as you say. Once i rendered it, everything i set on my state was there! And tnx for the callbackfunction and array spreading tips, they came very handy. – User 12345 May 19 '21 at 02:25
  • 1
    Great -- you can mark the answer as correct/accepted with the green checkmark and if you thought it was helpful, you can upvote with the arrow as well. – jnpdx May 19 '21 at 02:26
  • My bad, im new to stackoverflow ;) – User 12345 May 19 '21 at 02:28