I am trying to make REST call from a react component and render the returned JSON data into the DOM
Here is my component
import React from 'react';
export default class ItemLister extends React.Component {
constructor() {
super();
this.state = { items: [] };
}
componentDidMount() {
fetch(`http://api/call`)
.then(result=> {
this.setState({items:result.json()});
});
}
render() {
return(
WHAT SHOULD THIS RETURN?
);
}
In order to bind the returned json in a DOM?
There are a couple of errors in your code. The one that's probably tripping you up is the
this.setState({items:result.json()})
Fetch's
.json()
method returns a promise, so it will need to be dealt with as async.I don't know why
.json()
returns a promise (if anyone can shed light, I'm interested).For the render function, here you go...
Don't forget the unique key!
For the other answer, there's no need to bind map.
Here it is working...
http://jsfiddle.net/weqm8q5w/6/
You can try this for your render method:
and don't forget to use
.bind(this)
for yourfetch(...).then()
, I don't think it could work without...Use the following instead. It will work: (You can also check the data if loaded in the console)
Then use the result stored in state during render to display as required.
Fetch methods will return a Promise that makes it straightforward to write code that works in an asynchronous manner:
In your case:
result.json() returns a promise, because this it works on a response stream and we need to process entire response first in order to work.