DEV Community

Sandeep
Sandeep

Posted on

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.

Top comments (0)