Reputation: 15
I'm trying to access an API, and present the data in a graph. I have followed tutorials on using Fetch; for example this one: (https://appdividend.com/2018/08/20/javascript-fetch-api-example-tutorial/)
fetch('https://api.github.com/users/KrunalLathiya')
.then(res => res.json())
.then(json => console.log(json));
Which is lovely, it fetches the data and logs it into the console. But from what I can tell, the data is not available externally, how do I get the data displaying inside console.log(json)
, into the state, so I can then present it in a graph?
Upvotes: 0
Views: 503
Reputation: 1941
Katia Wheeler is correct. If you want to stay with the Promise only. Then inside you second then
where you have your console.log
you can use this.setState
.
fetch('https://api.github.com/users/KrunalLathiya')
.then(res => res.json())
.then(json => {
this.setState({
graphData: json,
})
});
Then you will have it in the component state and you can use it normally from there.
Upvotes: 0
Reputation: 549
Assign the response to a variable and then call setState
with the data like so:
UPDATED WITH ASYNC
const response = await fetch('https://api.github.com/users/KrunalLathiya')
.then(res => res.json());
this.setState({
data: response
});
Then you can access your response using this.state.data
in render for the graph.
Upvotes: 2