import{useState,useEffect}from'react';importaxiosfrom'axios';axios.defaults.baseURL='https://jsonplaceholder.typicode.com';/**
fixed :
- no need to JSON.stringify to then immediatly do a JSON.parse
- don't use export defaults, because default imports are hard to search for
- axios already support generic request in one parameter, no need to call specialized ones
**/exportconstuseAxios=(axiosParams)=>{const[response,setResponse]=useState(undefined);const[error,setError]=useState('');const[loading,setloading]=useState(true);constfetchData=async (params)=>{try{constresult=awaitaxios.request(params);setResponse(result.data);}catch(error){setError(error);}finally{setLoading(false);}};useEffect(()=>{fetchData(axiosParams);},[]);// execute once onlyreturn{response,error,loading};};
and to use it :
import{useAxios}from'axioshook';constApp=()=>{const{response,loading,error}=useAxios({method:'POST',url:'/posts',headers:{// no need to stringifyaccept:'*/*'},data:{// no need to stringifyuserId:1,id:19392,title:'title',body:'Sample text',},});return (<divclassName='App'><h1>Posts</h1>
{loading?(<p>loading...</p>
):(<div>{error&&(<div><p>{error.message}</p>
</div>
)}<div>{// no need to use another state to store data, response is sufficientresponse&&<p>{response.id}</p>
}</div>
</div>
)}</div>
);};
Hi, Em Muhammad Ayoub self-learned programmer from Faisalabad. I'm a professional web developer specialised in frontend development for complex scalable web apps.
I am a skilled Full-Stack Developer with a passion for creating robust systems and applications. With experience in developing various systems and applications, I have honed my expertise in JavaScript
There is small syntax error in losing callback. instead of setloading it should be setLoading. `import { useState, useEffect } from 'react';
import axios from 'axios';
Hello,
here is a reviewed code for final solution :
and to use it :
Exactly what I was thinking while reading the post XD. And maybe wrap this in React Query for an even juicier hook!
You can get it here :
httpss://github.com/ecyrbe/react-axios-query
It's juste a wrapper. Really simple.
Correct link :)
github.com/ecyrbe/react-axios-query
sir what if the structure has axios interceptor and header is with bearer token?
Hi, small fix:
here
const [loading, setloading] = useState(true);
to
const [loading, setLoading] = useState(true);
upperCase "L"
Greetings
Wow
A correction:
Add axiosParams to the empty list in the second param of the useEffect hook. This will remove a dependency error
There is small syntax error in losing callback. instead of setloading it should be setLoading. `import { useState, useEffect } from 'react';
import axios from 'axios';
axios.defaults.baseURL = 'jsonplaceholder.typicode.com';
/**
fixed :
`import { useState, useEffect } from 'react';
import axios from 'axios';
axios.defaults.baseURL = 'jsonplaceholder.typicode.com';
/**
fixed :
axios already support generic request in one parameter, no need to call specialized ones
**/
export const useAxios = (axiosParams) => {
const [response, setResponse] = useState(undefined);
const [error, setError] = useState('');
const [loading, setLoading] = useState(true);
const fetchData = async (params) => {
try {
const result = await axios.request(params);
setResponse(result.data);
} catch( error ) {
setError(error);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchData(axiosParams);
}, []); // execute once only
return { response, error, loading };
};`
This is a really good optimisation, specially the
axios.request
👏Two points to consider here -
JSON.stringify
andJSON.parse
was used to avoid possibility of any errors.Thanks for sharing this 🙌