0

This is my code:

state={
   data:{},
   place:''
};

handlePlaceChange = async (place) => {
   const fetchedData = await fetchData(place);
   this.setState({data:fetchedData, place:place});
   console.log(data);
}

I am getting fetchedData correctly and when I log it I get the expected object that I am passing from another file. But when i try to console log I get this error when i call the handlePlaceChange function.

Unhandled Rejection (ReferenceError): data is not defined.

But data is defined and it is a state variable!!!!

Hemant Parashar
  • 3,684
  • 2
  • 16
  • 23
maddy
  • 1
  • 1

2 Answers2

1

Replace data with this.state.data in console.log.

console.log(this.state.data)

Also, your state data will not get updated immediately. SO, console log will show you its initial value.

To check if your state has got fetched data as you want, put this console in render function.

Piyush
  • 3,015
  • 3
  • 18
  • 31
  • Yes that worked! Later I rendered the day in my component and it rendered fine... my console logging method was wrong that I was logging just data instead of this.state.data. Thanks a lot for your help! Much appreciated.... – maddy Jun 14 '20 at 19:15
0

You should extract the json data after fetching:

const fetchedData = await fetchData(place)
const data = await fetchedData.json()
this.setState({data, place:place})

Ah, the data is undefined because you're just logging undefined variable data, you should be logging to state data: this.state.data

console.log('fetched data: ', data, 'state data: ', this.state.data)

However, the state data you'll get initial as it's asynchronous.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231