DHIS2 Application Runtime Fetching

Refetching data

The useDataQuery hook caches the results of a dataQuery. This means that when you re-run the query it doesn't request the data from the DHIS2 instance again. It actually returns that data directly from the cache. This saves on bandwidth costs and speeds up the application.

Sometimes this is may be a problem. For example, when you have an API parameter that changes while the application is running. You can tell the useDataQuery to ignore the cached results and force it to run a new query by using the refetch() method.

Below is an example where data is refetched based on if the props to the component change. You can easily modify this to trigger on state changes by adding the relevant state variable to the useEffect array.

import { useState, useEffect } from 'react'
import { useDataQuery } from '@dhis2/app-runtime'
// Data Query with dynamic ID.
const dataQuery = {
dataSets: {
resource: 'dataSets',
id: ({ id }) => id,
params: {
fields: ['dataSetElements[dataElement[id, displayName,created]'],
paging: false,
},
},
}
// A component that takes a dataSet ID as a prop.
export function DatasetsTable({ id }) {
/*
A useDataQuery where we pass the id as a variable. Note that we also save the refetch
which allows us to run the query again at a later point.
*/
const { loading, error, data, refetch } = useDataQuery(dataQuery, {
variables: {
id: id,
},
})
/*
You can use useEffect to check if props change (and not just state).
We check if the ID prop has changed from the last run and then re-run the
dataQuery with the new id to get fresh data when a user clicks on a new ID.
*/
useEffect(() => {
refetch({ id: id })
}, [id])
if (loading) {
return <p>loading...</p>
}
if (data) {
return <p>{JSON.stringify(data)}</p>
}
}