Api Call in React

Calling API is every application’s need . in jquery we uses $.ajax() function for ajax calls.

in same way for react we will use axios package for react . axios makes it very easy for ajax calls in modern browser it uses fetch and in older browser it uses XMLHttpResponse for API calls

for installing axios dependency using npm package manager

$ npm install axios

now see the below example…

import React, {useState, useEffect} from 'react'
import Axios from 'axios'
export default function App(){
    const [items, setItems]= useState([])
    
    useEffect(()=>{
        Axios.get("https://jsonplaceholder.typicode.com/posts").then(d => {
            if(d.status == 200){
                setItems(d.data)
            }
        })
    },[])
    
    return(
        <div>
            <ul>
                {
                    items.map(list=>{
                        return <li>{list.title}</li>
                    })
                }

            </ul>
        </div>
    )
}

in above example we called get method of axios . similarly there are other methods like post, put, patch, delete

axios return Promises so we have used then method if you do not know about promise read some post about that.

useEffect() hook is same as componentDidMount() life cycle method of react. it will execute only when the attached component is fully mounted but for the same behavior you have to pass the second argument as empty array, otherwise it will execute for any state changes.

I have checked for success status response also and d.data stores all the response data from API

comments powered by Disqus