React Native – The Most Popular Best Ways To Make REST API Calls In React Native

Hello Readers, CoolMonkTechie heartily welcomes you in this article (The most popular best ways to make REST API Calls in React Native ).

In this article, we will learn about different best ways to make REST API Calls in React Native. Many mobile apps need to load resources from a remote URL. We may want to make a POST request to a REST API, or we may need to fetch a chunk of static content from another server.

Applications on the web and mobile devices often cannot store all the information that they need. Therefore, they have to reach out to the web to update data, retrieve data, or request a service from a third-party. The transaction that takes place between two devices (client and server) is called an API call. An API (application programming interface) typically will use the REST design paradigm to manage all how it can be accessed (called).

This article shows the fetch function and the axios library. Both methods achieve the same task, making an HTTP call, but they go about it in slightly different ways.

A famous quote about learning is :

” The expert in anything was once a beginner. “

So Let’s begin.

Using Fetch

React Native provides the Fetch API for our networking needs. Fetch will seem familiar if we have used XMLHttpRequest or other networking APIs before. The Fetch API is a built-in Javascript function. We can use fetch by providing the URL for the location of our content. This will send a GET request to that URL.

Making Requests

In order to fetch content from an arbitrary URL, we can pass the URL to fetch:

fetch('https://mywebsite.com/mydata.json');

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

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

We can follow at the Fetch Request docs for a full list of properties.

Handling The Response

The above examples show how we can make a request. Most times, we will want to do something with the response.

Networking is an inherently asynchronous operation. Fetch methods will return a Promise that makes it straightforward to write code that works asynchronously:

const getMoviesFromApi = () => {
  return fetch('https://reactnative.dev/movies.json')
    .then((response) => response.json())
    .then((json) => {
      return json.movies;
    })
    .catch((error) => {
      console.error(error);
    });
};

We can read through the above code like;

  1. Fetch the data at the URL 'https://reactnative.dev/movies.json'
  2. Then, transform the response into JSON
  3. Then, return the movies property on the JSON object
  4. If there is an error, log the error to the console.

We can also use the async / await syntax in a React Native app:

const getMoviesFromApiAsync = async () => {
  try {
    let response = await fetch(
      'https://reactnative.dev/movies.json'
    );
    let json = await response.json();
    return json.movies;
  } catch (error) {
    console.error(error);
  }
};

We need to catch any errors that may be thrown by fetch, otherwise they will be dropped silently.

Fetch Example

import React, { useEffect, useState } from 'react';
import { ActivityIndicator, FlatList, Text, View } from 'react-native';

export default App = () => {
  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch('https://reactnative.dev/movies.json')
      .then((response) => response.json())
      .then((json) => setData(json.movies))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
  }, []);

  return (
    <View style={{ flex: 1, padding: 24 }}>
      {isLoading ? <ActivityIndicator/> : (
        <FlatList
          data={data}
          keyExtractor={({ id }, index) => id}
          renderItem={({ item }) => (
            <Text>{item.title}, {item.releaseYear}</Text>
          )}
        />
      )}
    </View>
  );
};

By default, iOS will block any request that’s not encrypted using SSL. If we need to fetch from a cleartext URL (one that begins with http), then App Transport Security exception will first need to add.

It is more secure to add exceptions only for those domains, If we know ahead of time to need to access the domains; if we do not know the domains until runtime, ATS can completely disable.

This is a simple way to send HTTP requests as soon as possible. However, another popular method for sending HTTP requests is with third-party libraries.

Using XMLHttpRequest API

The XMLHttpRequest API is built into React Native. This means that we can use third-party libraries such as frisbee or axios that depend on it, or we can use the XMLHttpRequest API directly if we prefer.

var request = new XMLHttpRequest();
request.onreadystatechange = (e) => {
  if (request.readyState !== 4) {
    return;
  }

  if (request.status === 200) {
    console.log('success', request.responseText);
  } else {
    console.warn('error');
  }
};

request.open('GET', 'https://mywebsite.com/endpoint/');
request.send();

The security model for XMLHttpRequest differs from on web, as there is no concept of CORS in native apps.

Using WebSocket Protocal

React Native also supports WebSockets , a protocol which provides full-duplex communication channels over a single TCP connection.

var ws = new WebSocket('ws://host.com/path');

ws.onopen = () => {
  // connection opened
  ws.send('something'); // send a message
};

ws.onmessage = (e) => {
  // a message was received
  console.log(e.data);
};

ws.onerror = (e) => {
  // an error occurred
  console.log(e.message);
};

ws.onclose = (e) => {
  // connection closed
  console.log(e.code, e.reason);
};

Using Axios Library

The Axios is a Javascript library used to make HTTP requests, and it supports the Promise API that is native to JS ES6. The Axios library has grown in popularity alongside the increase in apps that exchange information using JSON. Three things that make the Axios library so useful are the ability to;

  • Intercept requests and responses
  • Transform request and response data
  • Automatically transform data for JSON

Axios Library Example

import Axios from 'axios'

Axios({
  url: '/data',
  method: 'get',
  baseURL: 'https://example.com',
  transformRequest: [function (data, headers) {
    // Do whatever you want to transform the data
 
    return data;
  }],
  transformResponse: [function (data) {
    // Do whatever you want to transform the data
 
    return data;
  }],
  headers: {'X-Requested-With': 'XMLHttpRequest'},
  data: {
    name: 'Some Name'
  },
})

In the above example, we have passed a configuration object that calls an example URL with a GET request. We’ll notice that some parameter names are common between fetch and Axios.

Next, let’s look at a smaller GET request.

axios.get('https://example.com/data')
  .then(function (response) {
    return response.names;
  })
  .catch(function (error) {
    console.log(error);
  })

We are calling the same URL as we did with the fetch API, but we don’t have to manually transform the response object into JSON. Axios has more features that can be useful with bigger applications.

That’s all about in this article.

Conclusion

In this article, we understood about different best ways to make REST API Calls in React Native. This article showed the fetch and axios library usage with code snippets in React Native .

Thanks for reading! I hope you enjoyed and learned about REST API Calls concepts in React Native. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find Other articles of CoolmonkTechie as below link :

You can also follow official website and tutorials of React Native as below links :

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING!!???

ReactJS – How To Use Axios with ReactJS ?

Hello Readers, CoolMonkTechie heartily welcomes you in this article (How To Use Axios with ReactJS ?).

In this article, we will understand how to use Axios with ReactJS. Many projects on the web need to interface with a REST API at some stage in their development. Axios is a lightweight HTTP client based on the $http service within Angular.js v1.x and is similar to the native JavaScript Fetch API. In this article, we will see examples of how to use Axios to access the popular JSON Placeholder API within a React application.

A famous quote about learning is :

” Change is the end result of all true learning.”

So Let’s begin.


Introduction

Axios is promise-based, which gives you the ability to take advantage of JavaScript’s async and await for more readable asynchronous code.

We can also intercept and cancel requests, and there’s built-in client-side protection against cross-site request forgery.


Prerequisites

To follow along with this article, we’ll need the following:

  • Node.js version 10.16.0 installed on our computer.
  • A new React project set up with Create React App.
  • It will also help to have a basic understanding of JavaScript along with a basic knowledge of HTML and CSS.


Steps to Use Axios library


Step 1 – Adding Axios to the Project

In this section, we will add Axios to the axios-tutorial React project. To add Axios to the project, open our terminal and change directories into our project:

$ cd axios-tutorial

Then run this command to install Axios:

$ npm install axios

Next, we will need to import Axios into the file we want to use it in.


Step 2 – Making a GET Request

In this example, we create a new component and import Axios into it to send a GET request.

Inside the src folder of our React project, create a new component named PersonList.js:

src/PersonList.js

import React from 'react';

import axios from 'axios';

export default class PersonList extends React.Component {
  state = {
    persons: []
  }

  componentDidMount() {
    axios.get(`https://jsonplaceholder.typicode.com/users`)
      .then(res => {
        const persons = res.data;
        this.setState({ persons });
      })
  }

  render() {
    return (
      <ul>
        { this.state.persons.map(person => <li>{person.name}</li>)}
      </ul>
    )
  }
}

First, we import React and Axios so that both can be used in the component. Then we hook into the componentDidMount lifecycle hook and perform a GET request.

We use axios.get(url) with a URL from an API endpoint to get a promise which returns a response object. Inside the response object, there is data that is then assigned the value of person.

We can also get other information about the request, such as the status code under res.status or more information inside of res.request.


Step 3 – Making a POST Request

In this step, we will use Axios with another HTTP request method called POST.

Remove the previous code in PersonList and add the following to create a form that allows for user input and subsequently POSTs the content to an API:

src/PersonList.js

import React from 'react';
import axios from 'axios';

export default class PersonList extends React.Component {
  state = {
    name: '',
  }

  handleChange = event => {
    this.setState({ name: event.target.value });
  }

  handleSubmit = event => {
    event.preventDefault();

    const user = {
      name: this.state.name
    };

    axios.post(`https://jsonplaceholder.typicode.com/users`, { user })
      .then(res => {
        console.log(res);
        console.log(res.data);
      })
  }

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <label>
            Person Name:
            <input type="text" name="name" onChange={this.handleChange} />
          </label>
          <button type="submit">Add</button>
        </form>
      </div>
    )
  }
}

Inside the handleSubmit function, we prevent the default action of the form. Then update the state to the user input.

Using POST gives us the same response object with information that we can use inside of a then call.

To complete the POST request, we first capture the user input. Then we add the input along with the POST request, which will give us a response. We can then console.log the response, which should show the user input in the form.


Step 4 – Making a DELETE Request

In this example, we will see how to delete items from an API using axios.delete and passing a URL as a parameter.

Change the code for the form from the POST example to delete a user instead of adding a new one:

src/PersonList.js

import React from 'react';
import axios from 'axios';

export default class PersonList extends React.Component {
  state = {
    id: '',
  }

  handleChange = event => {
    this.setState({ id: event.target.value });
  }

  handleSubmit = event => {
    event.preventDefault();

    axios.delete(`https://jsonplaceholder.typicode.com/users/${this.state.id}`)
      .then(res => {
        console.log(res);
        console.log(res.data);
      })
  }

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <label>
            Person ID:
            <input type="text" name="id" onChange={this.handleChange} />
          </label>
          <button type="submit">Delete</button>
        </form>
      </div>
    )
  }
}

Again, the res object provides us with information about the request. We can then console.log that information again after the form is submitted.


Step 5 – Using a Base Instance in Axios

In this example, we will see how we can set up a base instance in which we can define a URL and any other configuration elements.

Create a separate file named api.js. Export a new axios instance with these defaults:

src/api.js

import axios from 'axios';

export default axios.create({
  baseURL: `http://jsonplaceholder.typicode.com/`
});

Once the default instance is set up, it can then be used inside of the PersonList component. We import the new instance like this:

src/PersonList.js

import React from 'react';
import axios from 'axios';

import API from '../api';

export default class PersonList extends React.Component {
  handleSubmit = event => {
    event.preventDefault();

    API.delete(`users/${this.state.id}`)
      .then(res => {
        console.log(res);
        console.log(res.data);
      })
  }
}

Because http://jsonplaceholder.typicode.com/ is now the base URL, we no longer need to type out the whole URL each time we want to hit a different endpoint on the API.


Step 6 – Using async and await

In this example, we will see how we can use async and await to work with promises.

The await keyword resolves the promise and returns the value. The value can then be assigned to a variable.

handleSubmit = async event => {
  event.preventDefault();

  //
  const response = await API.delete(`users/${this.state.id}`);

  console.log(response);
  console.log(response.data);
};

In this code sample, the .then() is replaced. The promise is resolved, and the value is stored inside the response variable.

That’s all about in this article.


Conclusion

In this article, We understood how to use Axios with ReactJS. We explored several examples on how to use Axios inside a React application to create HTTP requests and handle responses.

Thanks for reading ! I hope you enjoyed and learned about the Axios library usage in ReactJS. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe to the blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find Other articles of CoolmonkTechie as below link :

You can also follow official website and tutorials of React as below links :

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING!!???

Exit mobile version