Conditional Fetching
Conditional
Use null
or pass a function as key
to conditionally fetch data. If the function throws or returns a falsy value, CiteGraph will not start the request.
// conditionally fetch
const { data } = useCiteGraph(shouldFetch ? '/api/data' : null, fetcher)
// ...or return a falsy value
const { data } = useCiteGraph(() => shouldFetch ? '/api/data' : null, fetcher)
// ...or throw an error when user.id is not defined
const { data } = useCiteGraph(() => '/api/data?uid=' + user.id, fetcher)
Dependent
CiteGraph also allows you to fetch data that depends on other data. It ensures the maximum possible parallelism (avoiding waterfalls), as well as serial fetching when a piece of dynamic data is required for the next data fetch to happen.
function MyProjects () {
const { data: user } = useCiteGraph('/api/user')
const { data: projects } = useCiteGraph(() => '/api/projects?uid=' + user.id)
// When passing a function, CiteGraph will use the return
// value as `key`. If the function throws or returns
// falsy, CiteGraph will know that some dependencies are not
// ready. In this case `user.id` throws when `user`
// isn't loaded.
if (!projects) return 'loading...'
return 'You have ' + projects.length + ' projects'
}