Building and publishing a DHIS2 app using the app platform
Creating a program list component
Data needs
Minimizing the amount of data we fetch reduces load on the server as
well as providing a smoother user experience. Since we only want to
display programs given their display name, that should also be the
only thing along with the program id we fetch. The id can, will
and often is useful to uniquely identify DHIS2 resources.
Now that we have identied our data needs, we can formulate a query to fetch the data.
const query = {programs: {resource: 'programs',params: {fields: ['id', 'displayName'],paging: 'false',},},}
Representation needs
We can represent and visualize the programs in an infinite number of ways, though we recommend to use official DHIS2 user interface components wherever applicable.
In this example we are going to render a simple Menu containing
MenuItemss with labels for all the different programs.
To use the official DHIS2 user interface React components we have to
add @dhis2/ui to our project (shown below).
yarn add @dhis2/ui
Using our query
We have defined our query, but not yet told the app-runtime to
execute it. To do that we are going to use the useDataQuery hook
provided by @dhis2/app-runtime.
Let us start by importing the hook from the library.
import { useDataQuery } from '@dhis2/app-runtime'
And finally using the hook in our component.
const { error, loading, data } = useDataQuery(query)
The hook gives us easy access to error and loading status as well as a
data object where the fetched data is going to be stored.
Representing our data
We can now use interface components to show the fetched data on the screen.
Let us start off by importing the components we need from @dhis2/ui-core.
import { Menu, MenuItem } from '@dhis2/ui'
A simple mapping from program objects to MenuItems is enough for our
use case.
<Menu>{data.programs.programs.map(({ id, displayName }) => (<MenuItem key={id} label={displayName} />))}</Menu>
Final ProgramList component
The code for the entire component is shown below. We'll place this
code in src/ProgramList.js.
import React from 'react'import { useDataQuery } from '@dhis2/app-runtime'import { Menu, MenuItem } from '@dhis2/ui'const query = {programs: {resource: 'programs',params: {fields: ['id', 'displayName'],paging: 'false',},},}const ProgramList = () => {const { error, loading, data } = useDataQuery(query)if (error) {return <p>Error</p>}if (loading) {return <p>Loading</p>}return (<Menu>{data.programs.programs.map(({ id, displayName }) => (<MenuItem key={id} label={displayName} />))}</Menu>)}export { ProgramList }