Valentin Grigorev
Valentin Grigorev

Reputation: 145

How to make a remote server call from a react component?

The thing is: I have a small react app and remote server (only url is known). Also, I know some of server methods, for example "GET /api/records" - to get all data from the server. How to communicate through this method?

I have a button, which starts a handler, where I use fetch.

getRecords() {
    fetch("http://xxx.xxx.xxx.xxx:3000/api/records/", {method: "GET"})
        .then((response) => console.log(response));
}

By the console.log, I receive a Response object. How can I get data from it?

Upvotes: 1

Views: 1458

Answers (1)

André Teixeira
André Teixeira

Reputation: 2572

From the handler you can hydrate your state with the response. Try:

getRecords() {
    fetch("http://xxx.xxx.xxx.xxx:3000/api/records/", {method: "GET"})
        .then(response => response.json())
        .then(data => {
             this.setState({
                 yourDataKey: data
             })
        })
}

From Google documentation:

The response of a fetch() request is a Stream object, which means that when we call the json() method, a Promise is returned since the reading of the stream will happen asynchronously.

So, the first then will convert the stream object to json, and the second then will save the json on the component state.

Upvotes: 1

Related Questions