Integrating React-native apps with back-end code using fetch API

January 29, 2018 0 Comments

Integrating React-native apps with back-end code using fetch API

 

 

Many people tend to get confused, how to integrate their back-end code( Node-express, Python-flask etc).

To solve this best way is to create a URL on server which takes data as json from server and process it and reply with json data, using a post request.

The two common methods are GET and POST:

  • GET — Requests data from a specified resource
  • POST — Submits data to be processed to a specified resource

But there are some limitations to GET requests as follows:

  • GET requests can be cached
  • GET requests remain in the browser history
  • GET requests can be bookmarked
  • GET requests should never be used when dealing with sensitive data
  • GET requests have length restrictions
  • GET requests should be used only to retrieve data

Some + points on POST requests:

  • POST requests are never cached
  • POST requests do not remain in the browser history
  • POST requests cannot be bookmarked
  • POST requests have no restrictions on data length

(Source: https://www.w3schools.com/tags/ref_httpmethods.asp)

In GET request the parameters are sent as url, which sometimes you don’t want. Like you may have some sensitive data for e.g. user-name and password, which needs to be hidden while making a request, so POST request is better alternative.

Also if you want to send data other that ASCII characters GET requests are not that handy, however POST is better in such cases.

But we can use GET as well, here for sake for an example, I have used POST.
Basic structure of communication.

For this fetch API (https://facebook.github.io/react-native/docs/network.html)provided by react-native comes to rescue.

It is very easy to use and can be used to make all kinds of requests, GET, POST etc. The basic structure of the fetch request looks like following:

fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
}).then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});

The above code has a basic fetch process followed by parsing JSON response and then doing something with the response.

The fetch method has ‘method’ parameter to specify type of request, here its ‘POST’ as described above why.

The headers contains the headers of the request you are making, this may contain Authorization token etc, here it has content-type and accept type.

The body contains the main part of request in which we will be sending our query data as parameter.

.then() is used as function which will execute after the fetch request completes.

first then parses the json data from the response of the server.

Second then plays with the parsed json data and performs some function.

Then there is a catch block which catches any error.

Sure why not, lets say we want to build a basic application which fetches some data using the Hasura data API.

For doing so make, we will use the /v1/query/ endpoint provided by Hasura, in which two tables articles and authors are already provided, so lets select author name from it.

You can use the hasura api-console to generate body of request or write it yourself.

The response of above request is:

Lets say we want to make an app, in which on click , An author name should be displayed by an alert box.

The code goes as follows

import React, { Component } from 'react';
import { TouchableOpacity, View, ActivityIndicator, Text, Alert} from 'react-native';
export default class App extends Component {
handlePress = async () => {
fetch('https://data.advance88.hasura-app.io/v1/query', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
"type": "select",
"args": {
"table": "author",
"columns": [
"name"
],
"limit": "1"
}
})
})
.then((response) => response.json())
.then((responseJson) => {
Alert.alert("Author name at 0th index: " + responseJson[0].name);
})
.catch((error) => {
console.error(error);
});
}
render(){
return(
<View style={{paddingTop: 50, paddingLeft: 50 }}>
<Text> Some other text </Text>
<Text> Some other text </Text>
<TouchableOpacity onPress={this.handlePress.bind(this)}>
<Text style={{paddingTop: 50, paddingLeft: 50, color: '#FF0000'}}> Click me to see the name </Text>
</TouchableOpacity>
</View> 
);
}
}

Here is the start screen:

When the text is clicked:

Congratulations you have made your first fetch api in react-native.

Similarly various endpoints can be configured in your server to play with json data.

Happy coding :)

Divyanshu Kumar


Tag cloud