Fetching data
useDataQuery()
useDataQuery is a react hook that is imported from the DHIS2 App Runtime. It is used for querying the API in the React code. Instead of creating HTTP requests, you create a dictionary of the resources you want to request. The useDataQuery hook then requests the data, deals with the request, and returns the data in a dictionary.
But, before we get ahead of ourselves with the technical details we should first create our dataQuery.
Using the API test tool
Creating data queries
The useDataQuery hook takes a dictionary as an argument. This dictionary syntax is similar
to an API call.
This API call:
/api/dataSets?pageSize=5&fields=id,displayName
Is the same as this dataQuery:
{"dataSetsQuery": {"resource": "dataSets","params": {"pageSize": 5,"fields": ["id, displayName"]}}}
Creating a dataQuery for our project
Our API queries are:
/api/dataSets/aLpVgfXiz0f?fields=name,id,dataSetElements[dataElement[id,displayName]]/api/dataValueSets?orgUnit=KiheEgvUZ0i&dataSet=aLpVgfXiz0f&period=2020
Our dataQuery is:
const dataQuery = {dataSets: {resource: 'dataSets/aLpVgfXiz0f',params: {fields: ['name','id','dataSetElements[dataElement[id, displayName]',],},},dataValueSets: {resource: 'dataValueSets',params: {orgUnit: 'KiheEgvUZ0i',dataSet: 'aLpVgfXiz0f',period: '2020',},},}
Add the dataQuery to Browse.js
Modify your Browse.js file to include the dataQuery.
import React from 'react'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() {return <h1>Browse</h1>}