How to load data from a server in React Native?


To load data from the server you can make use of the fetch API that is similar to XMLHttpRequest or any other networking api’s.

It is very easy to make a request to the server using fetch. Take a look at the following code −

fetch('https://jsonplaceholder.typicode.com/posts/1')
   .then((response) => response.json())
   .then((responseJson) => console.log(responseJson));

In above code we are fetching the JSON file https://jsonplaceholder.typicode.com/posts/1 and printing the data to the console. The simplest call to fetch() API takes in one argument i.e the path you want to fetch and it returns a promise with response.

The fetch api returns a promise with http response, to get the JSON body from the response we need to make use of the json() method.

The second param to the fetch api, is an object that can have the method i.e (GET, POST), headers , the data you want to post etc.

Here is a working example that shows how to get the data from the server and display to the user.

Example: GET data using fetch API

The data is initialized to empty at the start as shown below −

state = {
   data: ''
}

Details about componentDidMount()

The fetch API is called inside the componentDidMount() function. The componentDidMount() is called immediately after a component is mounted i.e after all the elements are rendered on the page.

Here is the code for same −

componentDidMount = () => {
   fetch('https://jsonplaceholder.typicode.com/posts/1', {
      method: 'GET'
   })
   .then((response) => response.json())
   .then((responseJson) => {
      console.log(responseJson);
      this.setState({
         data: responseJson
      })
   })
   .catch((error) => {
      console.error(error);
   });
}

The data from the url : https://jsonplaceholder.typicode.com/posts/1 is as follows −

{
   "userId": 1,
   "id": 1,
   "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
   "body": "quia et suscipit
suscipit recusandae consequuntur expedita et cum
reprehenderit molestiae ut ut quas totam
nostrum rerum est autem sunt rem eveniet architecto" }

We are interested in displaying the text inside body.

The data variable is updated using setState method as shown below −

this.setState({
   data: responseJson
})

So now this.state.data.body has the data from the server which can be used to display to the user as shown below −

render() {
   return (
      <View>
         <Text>
            {this.state.data.body}
         </Text>
      </View>
   )
}

Here is the working code to get data from server using fetch Api −

import React, { Component } from "react";
import { Text, View } from "react-native";
class HttpExample extends Component {
   state = {
      data: ''
   }
   componentDidMount = () => { fetch('https://jsonplaceholder.typicode.com/posts/1', {
      method: 'GET'
   })
   .then((response) => response.json())
   .then((responseJson) => {
      console.log(responseJson);
      this.setState({
         data: responseJson
      })
   })
   .catch((error) => {
      console.error(error);
   });
}
render() {
   return (
      <View>
         <Text>
            {this.state.data.body}
            </Text>
         </View>
      )
   }
}
const App = () => {
   return (
      <HttpExample />
   )
}
export default App

Output

Updated on: 01-Jul-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements