Open In App

How to load data from the server-side in React Native ?

In this article, we will see how to integrate the React Native app with backend code using fetch API. Networking is an inherently asynchronous operation.

React Native Fetch: Fetch is the best Promise-based networking API in JavaScript. The fetch allows you to make network requests similar to XMLHttpRequest(XHR). The fetch() method only has one mandatory argument: the URL of the resource you wish to fetch. To integrate React Native with fetch API, define a resource and pass that URI to the fetch() function, which returns the data based on the request and displays that data via the View component.



Making requests to server side: In order to fetch content from an arbitrary URL, you can pass the URL to fetch:

fetch('https://yourwebsite.com/yourdata.json');

Fetch also takes an optional second argument that allows you to customize the HTTP request. You may want to specify additional headers, or make a POST request:



fetch('https://server-url/<path>/', {
method: 'POST',
headers: {
  Accept: 'application/json',
  'Content-Type': 'application/json'
},
body: JSON.stringify({
  firstData: 'yourValue',
  secondData: 'yourOtherValue'
})
});

Example: In this example we will see how to load data from server URL and shown to the Flat list of react native in 3 simple steps. For the data, we have used the API endpoint from http://jsonplaceholder.typicode.com/users we have created the component in App.js.

Step 1: First we need to create a simple react native app.

react-native init apiExample

Or using Expo,

expo init apiExample

Here apiExample is the project name. If you don’t have react-native, first you need to install react native using npm or expo. You can use this https://www.geeksforgeeks.org/introduction-react-native/amp/ documentation to install and setup the react-native.

Step 2: Change your directory and entering to App.js file.

cd apiExample

Project structure:

project structure

Step 3: Write code in App.js to fetch data from API and we are using fetch function.




import React, { useEffect, useState } from "react";
import {View, Text, FlatList} from 'react-native';
  
export default function App(){
  const [users,setUsers] = useState([]);
  
  useEffect(()=>{
    fetchData()
  },[]);
    
  const fetchData = () => {
      .then(response => response.json())
      .then(jsonResponse => setUsers(jsonResponse))
      .catch(error => console.log(error))
  };
  
  const renderUser = ({item}) => {
    return (
      <View style={{margin:10,borderWidth:0.5,padding:10}}>
        <Text style={{color:"black",fontSize:16,fontWeight:"bold"}}>
          User {item.id}
        </Text>
        <Text style={{color:"black"}}>Username : {item.username}</Text>
        <Text style={{color:"black"}}>Name : {item.name}</Text>
        <Text style={{color:"black"}}>Email : {item.email}</Text>
      </View>
    )
  }
  return (
    <View style={{flex:1,backgroundColor:"white"}}>
      <FlatList
        data={users}
        renderItem={renderUser}
        keyExtractor={(item,index) => index.toString()}
        />
    </View>
  )
}

Step to run application: After write the code start the app to see the output. To start the app,

react-native run android

For ios,

react-native run ios

Output:

output


Article Tags :