Kirill Stas Kirill Stas - 1 month ago 9
React JSX Question

React + fetch request

I am reading this article fetch API and trying to understand how to work with fetch in React. Firstly, could you explain what is request headers ?

Than,
in angular we do something like:

$http.get('/someword').success(function(response) {
console.log('i got the data i requested');
var variable = response;
}


and than on server side in express I can write:

var app = express();
app.get('/thissomeword', function(req, res) {
console.log('I got a GET request')
res.json(someVariableWithData)
})


How to do the same with fetch ? And the main question where and when I need to do it ? I understand that i need after i get data to do this.setState({}) for using my data later, but HOW is for me huge conundrum.

Answer

Here you have great facebook documentation: https://facebook.github.io/react-native/docs/network.html with example that shows what you want

headers in request

Sometimes you need header in request to provide access token or content-type (especially in POST request)

fetch('https://mywebsite.com/endpoint/', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue',
  })
})

Promises instead of callbacks

In your example you pass callbacks (req and res) to your request, in fetch you have Promises so you get response as a paramether of then or error message in catch.

fetch('https://facebook.github.io/react-native/movies.json')
  .then((response) => response.json())
  .then((responseJson) => {
    return responseJson.movies;
  })
  .catch((error) => {
    console.error(error);
  });