Updating data with mutations
This tutorial is a continuation of the DHIS2 application runtime tutorial on Dynamic Data Queries.
In this section we will:
- Get started with data mutations
- Learn how to define these mutations
- Mutate data using the
useDataMutationhook
1. Getting startedโ
Prerequisitesโ
Make sure that you have the @dhis2/app-runtime dependency installed in your project:
yarn add @dhis2/app-runtime
What are data mutations?โ
Data queries are for reading information and data mutations are for writing or changing that information.
With the DHIS2 app runtime, we have 3 different types of mutation which translate directly to REST API requests:
| Mutation Type | REST requests |
|---|---|
| Create | POST |
| Update | PUT |
| Delete | DELETE |
2. Define data mutationsโ
In this example, we will continue building on the application from the previous tutorial and create a new program by clicking a button.
To start, let's create a separate file for our src/NewProgram.js component which we will import in the src/App.js.
Next, let's define a simple create mutation ๐
Create mutationโ
As with the data query definition from the previous tutorial, the create mutation below is also an object that specifies the resource programs from the DHIS2 Web API as well as the following required properties:
- The property
typeascreate(since we're creating a new program in this example) - The
dataproperty which is required in typecreate
The property names of data must correspond to the property names in the DHIS2 API.
// ...
const myMutation = {
resource: 'programs',
type: 'create',
data: {
name: 'A new Program',
shortName: 'A new Program',
programType: 'WITH_REGISTRATION',
},
}
// ...
3. Mutating dataโ
We have already declared our data mutation above so now we're ready to use it!
Let's start by importing the useDataMutation hook from the @dhis2/app-runtime