Fetching data
React Queries
The useDataquery that the DHIS2 App Runtime provides is essentially a wrapper around the library React Query.
Importing the useDataQuery hook
To use the useDataQuery hook we will need to import it in our Browse.js file.
import { useDataQuery } from '@dhis2/app-runtime'
Using the useDataQuery hook
The useDataQuery works like state. You put it inside of the component and it runs when the component is rendered.
const { loading, error, data } = useDataQuery(dataQuery)
The useDataQuery takes a dataQuery dictionary as an argument and returns three state variables: loading, error and data.
- The
loadingboolean is eithertrueorfalsedepending on if the request is currently being sent. - The
errordictionary isundefinedunless the API responded with an error, if so it will contain the error message. - The
datadictionary isundefineduntil the API has responded. It will then contain the data from API response.
Because only one of these variables will evaluate to true at the same time it's easy to display
different things depending on the state of the request.
if (error) {return <span>ERROR: {error.message}</span>}if (loading) {return <span>Loading...</span>}if (data) {console.log(data)}
Add the useDataQuery to Browse.js
Import useDataQuery and execute the dataQuery you created in the last step. Then console.log(data) the data the API responds with
when completed.
You should try implementing this yourself before looking at the solution below.
Solution:
import React from 'react'import { useDataQuery } from '@dhis2/app-runtime'const dataQuery = {dataSets: {resource: 'dataSets/aLpVgfXiz0f',params: {fields: ['name','id','dataSetElements[dataElement[id, displayName]',],},},dataValueSets: {resource: 'dataValueSets',params: {orgUnit: 'KiheEgvUZ0i',dataSet: 'aLpVgfXiz0f',period: '2020',},},}export function Browse() {const { loading, error, data } = useDataQuery(dataQuery)if (error) {return <span>ERROR: {error.message}</span>}if (loading) {return <span>Loading...</span>}if (data) {console.log(data)}return <h1>Browse</h1>}
Run this code and look at the data in the console. In the next step we will prepare our data.