Consume a REST API With Axios Client React

sabrinasuarezarrieta

sabrinasuarezarrieta

Posted on November 17, 2020

Consume a REST API With Axios Client React

APIs are what we can use to feed our React applications with data. APIs consist of a set of data, that is often in JSON format with specified endpoints. When we access data from an API, we want to access specific endpoints within that API framework. We can also say that an API is a contractual agreement between two services over the shape of request and response. The code is just a byproduct. It also contains the terms of this data exchange.

Axios is an easy to use promise-based HTTP client for the browser and node.js. Since Axios is promise-based, we can take advantage of async and await for more readable and asynchronous code. In this example, I'm going to show a list of crops that the user must water and how I get that list from an API.

First, we are going to import Axios in our project, in this case, I use npm

npm install axios
Enter fullscreen mode Exit fullscreen mode

Next, we define a service file where we are going to define the call to the service.

import axios from 'axios';

let urlBase = 'https://back-project.herokuapp.com/';
//Obtener informacion feedback
async function getCrops(code) {
  return await axios.get(`${urlBase}crops/list/${code}`)
    .then((response) => {
      return response.data;
    });
}

export const PrincipalService = {
  getCrops
}

Enter fullscreen mode Exit fullscreen mode

And in the component file, we call our service from a function and set our list of crops in the state to use the times we need.

getAllCropsByUser() {
      PrincipalService.getCrops(user).then(response => {
           //setIsLoading(false)
           this.setState({
              crops: response.crops
           });
        });        
    }
Enter fullscreen mode Exit fullscreen mode

Axios also provides a set of shorthand method for performing different HTTP requests. The Methods are:
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

Thank you soo much for reading and I hope this information will be helpful for all of you

đź’– đź’Ş đź™… đźš©
sabrinasuarezarrieta
sabrinasuarezarrieta

Posted on November 17, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related