Skip to content

Instantly share code, notes, and snippets.

@premsai2030
Created August 6, 2022 09:24
Show Gist options
  • Save premsai2030/eb705f5b44272d553ca8810565fc06f4 to your computer and use it in GitHub Desktop.
Save premsai2030/eb705f5b44272d553ca8810565fc06f4 to your computer and use it in GitHub Desktop.
Axios BoilerPlate with custom hook in React
import React, { useState, useEffect } from 'react';
import Axios from 'axios';
class ApiInterface {
constructor() {
this.axios = Axios.create({
baseURL: 'https://jsonplaceholder.typicode.com',
timeout: 3000,
});
this.methods = ['GET', 'POST', 'PATCH', 'PUT', 'DELETE'];
}
getMethod(httpMethod) {
if (!httpMethod) return 'GET';
else {
const index = this.methods.findIndex(
(method) => method === httpMethod.toUpperCase()
);
return this.methods[index];
}
}
getReqObj(payload) {
const method = this.getMethod(payload.method);
const url = payload.path || '';
const headers = payload.headers || {};
const data = payload.body || {};
const reqObj = {
url,
method,
data,
headers,
};
return reqObj;
}
async useAsyncAxios(payload) {
const reqObj = this.getReqObj(payload);
let response = null;
try {
response = await this.axios(reqObj);
response = response.data;
} catch (err) {
response = err;
}
return response;
}
useAxios(payload) {
const [isLoading, setIsLoading] = useState(false);
const [data, setData] = useState([]);
const [error, setError] = useState(null);
useEffect(() => {
const reqObj = this.getReqObj(payload);
setIsLoading(true);
this.axios(reqObj)
.then((response) => {
setData(response.data);
})
.catch((error) => {
setError(error);
})
.finally(() => {
setIsLoading(false);
});
}, []);
return [data, isLoading, error];
}
}
export default new ApiInterface();
@premsai2030
Copy link
Author

This code will run fine when you off the react-hooks in eslintrc.json or else we can use this boiler plate without class.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment