Web Designing World | Logo

Hello Guyz! How are you today I am going to show you that how to fetch HTTP request through a web API in react native. HTTP Request Fetch in React Native.

HTTP Request Fetch in React Native

Here is an interesting example of posting and fetching the data from the server. So Whenever you are connecting your application to a backend server (to get or post the data) you have to make an HTTP  request for fetching the data.

Code Snippet of Basic Network Call using React Native Fetch

fetch('Web URL HERE', {
    method: 'GET'
    //Request Type 
})
.then((response) => response.json())
//If response is in json then in success
.then((responseJson) => {
    //Success 
    console.log(responseJson);
})
//If response is not in json then in error
.catch((error) => {
    //Error 
    console.error(error);
});

In this example below, I am using an free demo APIs. The example has two-button each has its own onPress which triggers our services. It’s Just for the demo purpose, I am using react native buttons to trigger the request but If You need any data which needs to render while loading your screen you can use the componentDidMount lifecycle method to load the data from the server as soon as the component is mounted.

I am going to use react-native init to make our React Native App. Assuming that you have node installed, you can use npm(Node Packet Manager) to install the react-native-cli  command-line utility.

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the –version argument:

react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next

This will make a project structure with an index file named App.js in your project directory.

Code

Open App.js in any code editor and replace the code with the following code

App.js

//This is an example code to understand HTTP Requests// 
import React, { Component } from 'react';
//import react in our code. 
// Appfinz Technologies
import { StyleSheet, View, Button, Alert} from 'react-native';
//import all the components we are going to use. 

export default class App extends Component {

  getDataUsingGet(){
    //GET request 
    fetch('https://jsonplaceholder.typicode.com/posts/1', {
        method: 'GET'
        //Request Type 
    })
    .then((response) => response.json())
    //If response is in json then in success
    .then((responseJson) => {
        //Success 
        alert(JSON.stringify(responseJson));
        console.log(responseJson);
    })
    //If response is not in json then in error
    .catch((error) => {
        //Error 
        alert(JSON.stringify(error));
        console.error(error);
    });
  }

  getDataUsingPost(){
    //POST json 
    var dataToSend = {title: 'foo', body: 'bar', userId: 1};
    //making data to send on server
    var formBody = [];
    for (var key in dataToSend) {
      var encodedKey = encodeURIComponent(key);
      var encodedValue = encodeURIComponent(dataToSend[key]);
      formBody.push(encodedKey + "=" + encodedValue);
    }
    formBody = formBody.join("&");
    //POST request 
    fetch('https://jsonplaceholder.typicode.com/posts', {
      method: "POST",//Request Type 
      body: formBody,//post body 
      headers: {//Header Defination 
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
      },
    })
    .then((response) => response.json())
    //If response is in json then in success
    .then((responseJson) => {
        alert(JSON.stringify(responseJson));
        console.log(responseJson);
    })
    //If response is not in json then in error
    .catch((error) => {
      alert(JSON.stringify(error));
      console.error(error);
    });
  }
  render() {
    return (
      <View style={styles.MainContainer}>
        {/*Running GET Request*/}
        <Button title='Get Data Using GET' onPress={this.getDataUsingGet}/>
        {/*Running POST Request*/}
        <Button title='Get Data Using POST' onPress={this.getDataUsingPost}/>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  MainContainer :{
    justifyContent: 'center',
    flex:1,
    margin: 10
  }
});

To Run the React Native App

Open the terminal again and jump into your project using.

cd ProjectName

To run the project on an Android Virtual Device or on real debugging device

react-native run-android

or on the iOS Simulator by running

react-native run-ios (macOS only).

Check it Here

website designing company in rohini

Leave a Reply

Your email address will not be published. Required fields are marked *