DEV Community

Deepak Jaiswal
Deepak Jaiswal

Posted on

1 1 1 1

Use axios as better practice in ReactJS

in this post i explain use axios as in ReactJS as better practice.you all kown very well axios handle http request in single promise.

Use axios as http

import axios from 'axios';

export let URL="http://localhost:5000/api/v1";
export let URL_PROFILE="http://localhost:5000/uploads/avatar/";
export let URL_POST="http://localhost:5000/uploads/posts/";
export let AUTH_TOKEN=localStorage.getItem('token')||'';

axios.defaults.baseURL = URL;
axios.defaults.headers.common['x-auth-token'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';


export const http=axios;

Enter fullscreen mode Exit fullscreen mode

and use http in your services like

import { http, URL } from "./http.service";
import { errorHandler } from "./error.service";

export const getAllTags=async ()=>{
    try {
        let resp=await http.get(URL+'/tag/all/tags')
        return resp;
    } catch (error) {
        errorHandler(error)
    }
}
Enter fullscreen mode Exit fullscreen mode

it is better practice to use axios in your application
and when you change your default token like this

import { http} from "./http.service";
export const setToken=(token)=>{
  axios.defaults.headers.common['x-auth-token'] = token;
}
Enter fullscreen mode Exit fullscreen mode

use error handler

import { toast } from "react-toastify"

export const errorHandler=(error)=>{
   if(error.message==="Network Error" && error.status===500){
        toast.error(error.message)
   }
   toast.error(error?.response?.data?.message)
}
Enter fullscreen mode Exit fullscreen mode

I think you better understanding of axios better practice to use. thank you.

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay