8. API CALLS - fetch() vs axios()

Ayush RajputAyush Rajput
2 min read
  1. What is an API ?(Application Programming Interface)

    An API is a bridge that allows two programs or services to talk to each other by sending and receiving structured data (usually JSON).

    In MERN:

    • Backend (Node.js + Express + MongoDB) provides the API

    • Frontend (ReactJS) calls those APIs

  1. Basic API with express JS

     const express = require('express');
     const mongoose = require('mongoose');
     const cors = require('cors');
    
     const app = express();
     app.use(cors());
     app.use(express.json()); // parse JSON body
    
     mongoose.connect('mongodb://localhost:27017/apidemo')
         .then(() => console.log('MongoDB connected'))
         .catch(err => console.log(err));
    
     // Sample schema
     const User = mongoose.model('User', {
         name: String,
         email: String
     });
    
     // Routes
     app.get('/api/users', async (req, res) => {
         const users = await User.find();
         res.json(users);
     });
    
     app.post('/api/users', async (req, res) => {
         const newUser = new User(req.body);
         await newUser.save();
         res.status(201).json(newUser);
     });
    
     const PORT = 5000;
     app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
    
  2. Fetching API in reactJS using axios

    Axios is a promise-based HTTP client for the browser and Node.js. It's used to make API requests, like GET, POST, PUT, and DELETE.

    ๐Ÿ”„ Similar to fetch(), but more powerful and easier to use in many cases.

// Create axios Instance
import axios from 'axios'  // npm i axios
export const axiosInstance = axios.create({})
export const apiconnector = (method , url , bodyData , headers , params)=>{
    return axiosInstance({
        method:`${method}`,
        url:`${url}`,
        data: bodyData ? bodyData:null,
        headers: headers ? headers:null,
        params:params ? params:null,
    })
}

// Example of api call
export function signUp(accountType , firstName, lastName , email , password , confirmPassword,otp,navigate){
    return async(dispatch)=>{
        const toastId = toast.loading("Loading..." )
        dispatch(setLoading(true))
        try{
            const response = await apiconnector("POST" ,  SIGNUP_API , {accountType , firstName, lastName , email , password , confirmPassword,otp})
            console.log("SIGNUP API RESPONSE............", response)
            if (!response.data.success) {
                throw new Error(response.data.message)
            }
            toast.success("Account Created! Please Login") 
            navigate('/login') 
        }
        catch(err){
              console.log("SIGNUP API ERROR............", err)
              toast.error(err.response.data.message)
              navigate("/signup")
        }
        dispatch(setLoading(false))
        toast.dismiss(toastId)
    }
}

For small applications - No need to create instances (direct call)

   const fetchOrders = async()=>{
        try{
            const response = await axios.get(`${url}/userorders`, {headers:{token}});
            console.log(response.data.orders);
            setData(response.data.orders);
        }
        catch(err){
            console.log(err);
        }
    }
    useEffect(()=>{
        if(token){   //only for loggedin users
        fetchOrders();
        }   
    },[token])
  1. axios() vs fetch()

    axios() - Axios handles content-type and JSON conversion automatically.

    - Not a built in , need to install using npm package

    - Perfect for complex applications for compelex apis

    - Axios is simpler and handles errors more gracefully by default.

    - support in Nodejs (great for SSR and backend too)

    fetch() - need to convert in json manually

    - built in

    - perfect for lightweight application

    - Not support in Nodejs

Axios is a feature-rich HTTP client with great dev experience.
Fetch is native, modern, and perfect for lightweight apps.

0
Subscribe to my newsletter

Read articles from Ayush Rajput directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ayush Rajput
Ayush Rajput