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
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
}
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
});
});
}
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
Top comments (0)