Skip to content

Instantly share code, notes, and snippets.

@abhimanyuPatil
Created March 8, 2022 07:04
Show Gist options
  • Save abhimanyuPatil/98bd87ae1dd0c0e5cb7ba8a44cc378ac to your computer and use it in GitHub Desktop.
Save abhimanyuPatil/98bd87ae1dd0c0e5cb7ba8a44cc378ac to your computer and use it in GitHub Desktop.
Custom hook widely used to fetch and set data
export const fetchData = (params:Record<string,string>) => {
const [loading,setLoading] = useState(true)
const [data,setData] = useState([])
const [errorMsg,setErr] = useState("")
useEffect(()=>{
// axios call
axios.get(`/someUrl`)
.then(res=>{
setData(res.data)
setLoading(false)
})
.catch(err=>{
setLoading(false)
setErr("some error message")
})
},[params])
return {loading,data,errorMsg}
}
const AnyComp = ()=>{
const {loading,data,errorMsg} = fetchData()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment