0

  // Get location manually and fetch weather data
  getSearchLocation = (value) => {
    const weatherApiLink = `https://api.openweathermap.org/data/2.5/weather?q=${value}&appid=${apiKeys.weatherKey}&units=metric`;
this.setState({
      weatherApiLink,
      value
    })
    console.log(value)
    console.log(this.state.value)
    console.log(this.state.weatherApiLink)
  }

The getSearchLocation gets its value from other components using props and is run on the onClick function. when the above function is executed and we run the conslole.log(value) it returns the correct value but when we run console.log(this.state.value) it returns UNDEFINED on the first click, on the second click the state is updated

Zian Ejaz
  • 23
  • 4
  • 1
    You are logging the state value right after you have set it in the same function, but `setState` is async, hence you do not get the new value right after setting it. However, setting the state will cause a rerender. In the new render cycle it is guaranteed that the new value is set. The reason why it works on the second click is because the state has changed at that time. Try console.log outside of the function on the top level of the component and you will notice that it changes correctly on first click. – David Scholz May 01 '22 at 22:07
  • Thanks for the reply, The state is updated but the changes are not shown in the DOM, – Zian Ejaz May 01 '22 at 22:25

0 Answers0