Adel Benyahia
Nov 17, 2022

--

Thanks for sharing πŸ‘
fetching data in useEffect hook using Axios

const [data, setData] = useState(null);
const [isLoading, setIsloading] = useState(false);
const [error, setError] = useState(null);

useEffect(() => async ()=> {

setIsloading(true);
const controller = new AbortController();
try {
const result = await axios.get('url...', {
signal: controller.signal
});
setData(result?.data);
setError(null);
setIsloading(false);
} catch (err) {
setData(null);
setIsloading(false);
setError(err?.response?.message);
}
return () => { controller?.abort() };

};
}, []);

Explanation:

useEffect(() => async ()=> {…
In this line we converted useEffect to async arrow function, and we can use await

Results are stored in data state
Loading state are stored in isLoading

And errors in error state

--

--

Adel Benyahia

Web application developer (HTML β”‚ CSS β”‚ JS | ReactJS | NextJS | NestJS | MERN)