How can I use app-runtime to get and post data from the datastore

I saw the method below using getInstance from ‘d2’ get and post data to the datastore

import { getInstance } from 'd2'

export const NAMESPACE = 'dashboard'

export const hasDashboardNamespace = async (d2) =>
    await d2.currentUser.dataStore.has(NAMESPACE)

const getNamespace = async (d2) => {
    const hasNamespace = await hasDashboardNamespace(d2)

    return hasNamespace
        ? await d2.currentUser.dataStore.get(NAMESPACE)
        : await d2.currentUser.dataStore.create(NAMESPACE)
}

export const apiPostUserDataStoreValue = async (key, value) => {
    const d2 = await getInstance()
    const ns = await getNamespace(d2)

    return ns.set(key, value)
}

export const apiGetUserDataStoreValue = async (key, defaultValue) => {
    const d2 = await getInstance()
    const ns = await getNamespace(d2)
    const hasKey = ns?.keys?.find((k) => k === key)

    if (hasKey) {
        return await ns.get(key)
    } else {
        await apiPostUserDataStoreValue(key, defaultValue, ns)
        console.log('(These errors to /userDataStore can be ignored)')
        return defaultValue
    }
}

How can I use the useDataQuery, useDataMutation from app-runtime to do same? I mean the resource endpoint to call and if mutation is allowed in datastore

Hi @jetisco4u

I’m not sure I understand your question exactly. Would you share what you are trying to do exactly?

Thank you!

The d2 library is deprecated, so we do not recommend its use.

For useDataQuery and useDataMutation, please refer to the documentation for these hooks (useDataQuery Hook | DHIS2 Developer Portal) and look at some of the tutorials (Data Query | DHIS2 Developer Portal).

2 Likes

I don’t know why the developer site is not opening on my system recently

But are you saying I can use the useDataQuery and useDataMutation to get and post data to the datastore? Because I normally use the api endpoint

Yes the useDataQuery and useDataMutation hook into the API under the hood, making it easier for you to use.

Regarding the website not working, does it work for you again?

1 Like

It is working now

1 Like