Skip to content

Instantly share code, notes, and snippets.

@abhimanyuPatil
Created July 25, 2022 17:29
Show Gist options
  • Save abhimanyuPatil/ba2fb189a108ef56d872d0664489e479 to your computer and use it in GitHub Desktop.
Save abhimanyuPatil/ba2fb189a108ef56d872d0664489e479 to your computer and use it in GitHub Desktop.
Fetch Data on mount
import {useEffect, useState} from 'react';
import AxiosConfig from '../services/axiosConfig'; // use your axios config
export function getDataOnMount<T>(endpoint: string, dependency: any[]) {
const [loading, setLoading] = useState(true);
const api = new AxiosConfig();
const [data, setData] = useState<T>();
const [errorMsg,setErr] = useState("")
useEffect(() => {
const getData = () => {
api
.getRequest(endpoint)
.then(res => {
setData(res.data);
setLoading(false);
})
.catch(error => {
console.log('get error');
setLoading(false);
setErr("some error message")
});
};
getData();
}, [...dependency]);
return {loading, data};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment