'Add' function not working in useSavedObject Hook

Hi Dev Team,

I am facing a TypeError " Add is not a function" when I try adding a value to an object using the useSavedObject Hook as described in the latest DHIS2 Web Data Store Tutorial on Youtube.

I am on DHIS2 2.34.1 and use the following package “@dhis2/app-service-datastore”: “^1.0.0-alpha.2”

Please find below the code that I am running, any idea what I am missing?

import { useSetting, useAllSettings, useSavedObject, useSavedObjectList } from ‘@dhis2/app-service-datastore’;
import {useConfig} from ‘@dhis2/app-service-config’;

const configurationFile = () => {
const [savedObject, {add, update, replace, remove}] = useSavedObject(‘baseUrl’)
const {baseUrl} = useConfig()

  add({'baseUrl':baseUrl}) <-ERROR



}

Hello @dieng

the useSavedObject hook only does update, replace, remove functionalities. These will be done to the key you provided as a parameter to the hook.

If you want to add a new key to the savedObjects, you could use useSavedObjectList hook which provides the add function.

For your code it could be something like;

import {  useSavedObjectList } from ‘@dhis2/app-service-datastore’;
import {useConfig} from ‘@dhis2/app-service-config’;

const configurationFile = () => {
const [savedObjectList,{add}] = useSavedObjectList()
const {baseUrl} = useConfig()

add({baseUrl: baseUrl});

If you had already set the baseUrl key on the savedObject and need to modify or delete it, then you can use the useSavedObject hook ;

...
const [oldBaseUrl, {remove, replace, update}] = useSavedObject('baseUrl')
const {baseUrl: newBaseUrl} = useConfig()

remove() //Does not accept any arguments
update(newBaseUrl)
replace(newBaseUrl)

For more info, the most recent documentation for the @dhist2/app-service-datastore can be found on the package repository’s readme

I hope this helps

4 Likes

@nnkogift that is exactly correct!

@dieng I am not sure useSavedObject is what you want here - the baseUrl should be accessible with the useConfig hook from any component in your application. Are you saving multiple “saved objects” or saving any additional information in your saved object?

2 Likes

@nnkogift As usual, thank you for your clear and prompt response, I got the gist of it and was able to save all I wanted!

Hi @austin Thanks for checking in, I will be saving one saved object for an App that can adapt itself to different DHIS2 instance with different baseURL. I will then use the useSavedObject Hook to update specific keys.

1 Like