Updating JSON Data OnChange

I have an array form that allows users to add up to three address types (work, home, alternate contact). There is a checkbox on the form to indicated which of these is the preferred address. If, for example, work is checked off, but the user decides that want to change that to home, when they check the home object’s preferred checkbox, the work checkbox should become unchecked.

I feel like this should be pretty straightforward, I’m simply checking if I certain type of custom checkbox has been interacted with and then modifying the data as needed in JsonForms’s onchange event (see below), as per this topic: Modifiying jsonformsData after onChange.

The console shows the data was correctly updated, but the custom checkbox never re-renderers with the correct state. Any ideas about why that may be happening?


<JsonForms
      ajv={ajv}
      schema={schema}
      uischema={uischema}
      data={data ?? ''}
      renderers={renderers}
      cells={materialCells}
      validationMode="ValidateAndHide"
      onChange={({ data, errors }) => {
        let updatedData = data;
        if (updatedControl) {
          console.log('updatedControl', updatedControl);

          updatedData = enforceRule(updatedControl, updatedData);
          setUpdatedControl(undefined);
        }

        console.log('onChange', updatedData);
        setData(updatedData);
        setformErrors(errors);
      }}
    />

Hi @RTyska,

From what you posted the code should work in case the non-posted methods do what they are supposed to. If it doesn’t work for you, you need to check whether enforceRule returns a new root object and/or correctly updates the data. In case you have a custom boolean renderer, it needs to make sure to display the new value which comes in via the data prop.


However I think conceptually the code can be improved. It looks to me that you have custom renderers which set some “outside” marker, i.e. updatedControl and based on that state you update the data differently outside of JSON Forms.

If you already have custom renderers for the checkboxes anyway, then this approach can be simplified. Instead of doing the “outside” handling, simply adjust the value of the other checkboxes within your custom renderer. For example by calling handleChange not only on the respective boolean of the custom renderer, but also calling handleChange on all the booleans of the rest of the array. As you are in a custom renderer anyway, you can easily inject the whole array data into your props or access it manually with the useJsonForms hook in your custom renderer.

However you actually don’t need any custom renderer at all by leveraging the new middleware support. See here for the documentation.