How to handle API request and response in react using Axios

What is API?

API is the Application Programming Interface that is used to connect two different software or technology. API is very productive in development purposes as the backend is created in specific software and then it can be used with multiple frontend libraries to create different user interfaces.

Types of API Requests

There are multiple types of requests that can be made to fetch data from API.
Like sometimes we have to send data to a database to store information, sometimes we came to a situation where we have to delete data or update existing data or simply fetch data.
We usually called in CURD (create, update, read, delete)

Axios can make different requests in different situations. Axios provides specific functions to carry out type requests.
1. READ

axios.get(`URL`) or axios(‘URL`)

By default, axios carry out the read function

2. Create
We use it to post or send data to create or store new data in the database. Here we use the form to take input and send it with API call using a post request

axios.post(`URL`,body)

where the body is data that is to be sent and stored in a variable named body.

3. UPDATE
We can update specific data by targeting individual data and sending new or updated information along with it.

axios.put(`URL`,updatedbody)

here we are not using post because the post will change all fields of data which hasn’t been updated and set them to null. Put only updated the specific fields provided and the rest fields are unchanged.

4. DELETE
Simple as the name suggests this request is used to delete the data in a database or could serve.

axios.delete(`url`)

this will delete the specific data that has been in the database.

Every request is answered with a response but not every response is correct. The response is made on the basis of whether the request is correctly made or not. If yes the status code is 200 and a valid response is sent. But if any mistake or error in response different status codes like 404,400 is sent along with the error message.

Handling API in React

API can be handled by using specific functions like ‘fetch’ or functions from packages like ‘axios’. They are used to make URL requests with specific details like type of request authentication or body. Then this function returns some value or data that can be used.

To install the Axios package use the following command in terminal

npm install axios

The data returned may take some time and that has to be in synchronization with the rest software and to solve this issue we use the ASYNC function or then() function to let the process execute and make synchronization with the rest app. This helps to avoid the breakdown of the application as some information might be mandatory to load the specific pages.

AXIOS

axios(`http://localhost:8084/api/hm/user/search/getAuthentication?userName=${userName}&password=${password}`)
        .then(data=>{
            console.log(data)
            localStorage.setItem("user",JSON.stringify(data.data))
            dispatch({type:"USER",payload:data.data})
            
            history.push('/landing')
        }).catch((err) =>{
            setValues({...values,error:true});
            
             console.log(err)
        }
            
        )

The above API is called using the interface and the following is the data returned and used in REACT.

FETCH

fetch("/auth/signin",{
            method: "post",
            headers: {
                "Content-Type": "application/json"
            },
            body:JSON.stringify({
                email,password
            })
        }).then(res=>res.json())
        .then(data=>{
            if(data.error){
                M.toast({html:data.error,classes:"#c62828 red darken-3"})
            }else{
                localStorage.setItem("jwt",data.token)
                localStorage.setItem("user",JSON.stringify(data.user))
                dispatch({type:"USER",payload:data.user})
                history.push("/")
            }
        }).catch(err=>{
            console.log(err);
        })

In the end, it’s on the choice of what to use there are even more packages (eg: – request,supergent) to handle URLs but the method to use same.

Handle API request in react using Axios

Here we called the login API in React and using axios. This will fetch the data in the form of RESPONSE

Handle API response in react using Axios

This is the response of the API request and will be used in the REACT.