Created
August 6, 2022 09:24
-
-
Save premsai2030/eb705f5b44272d553ca8810565fc06f4 to your computer and use it in GitHub Desktop.
Axios BoilerPlate with custom hook in React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code will run fine when you off the react-hooks in eslintrc.json or else we can use this boiler plate without class.