I am new to javascript and Reactjs and I am trying to fetch data from an api and then set an variable in my state to that data. When I console.log the response after I convert it to JSON, it works fine. However, after I set the data in this.state to the response and try to console.log(this.state.data) in my state, it shows an empty object in the console.
import React, {Component} from 'react';
import './App.css';
import Plot from 'react-plotly.js';
class App extends Component{
constructor(){
super();
this.state = {data: {}}
}
componentDidMount(){
fetch("https://alpha-vantage.p.rapidapi.com/query?symbol=TSLA&function=GLOBAL_QUOTE", {
"method": "GET",
"headers": {
"x-rapidapi-host": "alpha-vantage.p.rapidapi.com",
"x-rapidapi-key": "230d86db60msheb2e40d44790598p1915e2jsn5074c9944675"
}
})
.then(response => response.json())
.then(response => {
console.log(response)
this.setState({data: response})
})
console.log(this.state.data)
}
render(){
return(
<h1></h1>
)
}
}
export default App;