Skip to content

Instantly share code, notes, and snippets.

@KitsonBroadhurst
Created June 8, 2020 11:20
Show Gist options
  • Save KitsonBroadhurst/ef6ca9564090957131d372b1fc881a30 to your computer and use it in GitHub Desktop.
Save KitsonBroadhurst/ef6ca9564090957131d372b1fc881a30 to your computer and use it in GitHub Desktop.
useFetcher Hook
import React, { useState, useEffect } from 'react'
// fetchOptionsGenerator is a bespoke header generator for our use case
import fetchOptionsGenerator from "./fetchOptionsGenerator"
/**
* Data fetching hook which takes a route url as a string
* and returns data from the backend for that route, along with a loading and error variable
* @param route: string
*/
const useFetcher = (route: string) => {
const [data, setData] = useState(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
const headerOptions = { tenantId: (window as any).tenantId || null }
useEffect(() => {
let didCancel = false;
(async function() {
try {
const params = fetchOptionsGenerator(headerOptions)
const response = await fetch(route, params)
const data = await response.json()
if (!didCancel) {
setLoading(false)
setData(data)
}
} catch (e) {
if (!didCancel) {
console.log("there was a problem with useFetch", e)
setError(e)
setLoading(false)
}
}
})()
return () => {
didCancel = true
}
}, [route])
return { data, loading, error }
}
export default useFetcher
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment