Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making REST calls from a react component

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?

like image 967
user_mda Avatar asked May 27 '16 14:05

user_mda


People also ask

How fetch data from React to API?

Using the JavaScript Fetch API. The Fetch API through the fetch() method allows us to make an HTTP request to the backend. With this method, we can perform different types of operations using HTTP methods like the GET method to request data from an endpoint, POST to send data to an endpoint, and more.


1 Answers

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.

fetch(`http://jsonplaceholder.typicode.com/posts`) .then(result=>result.json()) .then(items=>this.setState({items})) 

I don't know why .json() returns a promise (if anyone can shed light, I'm interested).

For the render function, here you go...

<ul>    {this.state.items.map(item=><li key={item.id}>{item.body}</li>)} </ul> 

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/

like image 164
D. Walsh Avatar answered Oct 03 '22 04:10

D. Walsh