useDataQuery params for multiple org units

Hi

How do I use the useDataQuery hook if I would like to get the datavalues for multiple org units and the same dataelement and monthly periods for multiple months?
const dataQuery = {

  dataValueSets: {
      resource: 'dataValueSets',
      params: {
          orgUnit: {orgUnitId},
          dataElement: {dataElementId},
          period: {period},
      },
  },

}

const { loading, error, data } = useDataQuery(dataQuery);

Can the params be in an array or to I have to call the dataquery for each combo?

Kind regards
Pooben

Hello @Pooben

You can pass multiple organisation units in the query as an array (check here).

Example query:

{
  "values":{
      "resource": "dataValueSets",
      "params": {
          "orgUnit":["ueuQlqb8ccl", "Rp268JB6Ne4", "cDw53Ej8rju"],
          "period": ["202303"],
          "dataElement": ["fbfJHSPpUQD"]
      }
  }
}

Which would result into the request
https://play.dhis2.org/2.39.2.1/api/32/dataValueSets?orgUnit=ueuQlqb8ccl,Rp268JB6Ne4,cDw53Ej8rju&period=202303&dataElement=fbfJHSPpUQD
If your parameters are dynamic, you can use dynamic queries to accomplish that.

Hope this helps.

Regards.

1 Like

Hi @nnkogift

Thank you for your assistance. How would I implement it, I have to loop through items to get datavalues:-

unitData.map((dataUnit) => {
const query = {

   dataValues: {
       resource: 'dataValues',
       params:
           ou: dataUnit.ou,
           de: dataUnit.de,
           pe: dataUnit.pe,
           co: dataUnit.co,
   },

}

const { loading, error, data } = useDataQuery(dataQuery);
console.log(data);
return {
…dataUnit,
value : dataValue.dataValues[0]
}
});

I am encountering an:-
ERROR

Invalid hook call. Hooks can only be called inside of the body of a function component.

Kind regards
Pooben

Hello @Pooben

Using a hook in a loop breaks React’s rules of hooks, see here.

To get data for multiple dataValues I suggest you use dynamic query.

const query = {
	values: {
		resource: "dataValues",
		params: ({ou, pe, de, co}) => ({
			ou,
			pe,
			de,
			co
		})
	}
};

You can group dimensions from the items, something like;

const ou = unitData.map(dataUnit) => dataUnit.ou);
const pe = unitData.map(dataUnit) => dataUnit.pe);
const de = unitData.map(dataUnit) => dataUnit.de);
const co = unitData.map(dataUnit) => dataUnit.co);

Then at the top level of your component, you can use the useDataQuery hook, passing your grouped dimensions as variables;

function MyComponent() {
	const {data, loading, error} = useDataQuery(query, {
		variables: {
			ou,
			pe,
			de,
			co
		}
	});

console.log(data)
}

Regards.

2 Likes