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.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay