Created
July 25, 2022 17:29
-
-
Save abhimanyuPatil/ba2fb189a108ef56d872d0664489e479 to your computer and use it in GitHub Desktop.
Fetch Data on mount
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 {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