1
Fork 0
mirror of https://github.com/pds-nest/nest.git synced 2024-11-23 05:24:18 +00:00
pds-2021-g2-nest/nest_frontend/hooks/useBackend.js

61 lines
1.9 KiB
JavaScript
Raw Normal View History

2021-05-11 14:37:15 +00:00
import { useCallback, useState } from "react"
/**
* Hook which fetches data from the backend on the first render of a component.
*
2021-05-11 15:21:09 +00:00
* @param fetchData - The function to use when fetching data, usually created by GlobalServer or GlobalUser.
* @param method - The HTTP method to use.
* @param path - The HTTP path to fetch the data at.
* @param body - The body of the HTTP request (it will be JSONified before being sent).
* @param init - Additional `init` parameters to pass to `fetch`.
*/
2021-05-11 14:38:56 +00:00
export default function useBackend(fetchData, method, path, body, init) {
const [error, setError] = useState(null)
const [data, setData] = useState(null)
const [loading, setLoading] = useState(false)
/**
* Load data from the API.
*/
const load = useCallback(
async () => {
console.debug(`Loading ${method} ${path}...`)
setLoading(true)
console.debug(`Fetching ${method} ${path}...`)
try {
const _data = await fetchData(method, path, body, init)
console.debug(`Displaying data of ${method} ${path}: `, _data)
setData(_data)
2021-05-11 14:37:15 +00:00
}
catch(e) {
console.debug(`Displaying error of ${method} ${path}: `, e)
setError(e)
2021-05-11 14:37:15 +00:00
}
finally {
console.debug(`Stopping loading of ${method} ${path}...`)
setLoading(false)
}
},
2021-05-11 14:37:15 +00:00
[fetchData, method, path, body, init],
)
/**
* Invalidate the data loaded from the API and try to load it again.
*/
2021-05-07 23:40:49 +00:00
const fetchNow = useCallback(
async () => {
console.debug("Clearing data...")
setData(null)
console.debug("Clearing error...")
setError(null)
await load()
},
2021-05-11 14:37:15 +00:00
[load],
)
2021-05-11 14:37:15 +00:00
return { data, error, loading, fetchNow }
}