Custom update data

Hi All,

I have various different places throughout my JSON forms app where I edit the data not using the controls on the page. For example I have an import functionality that reads in a JSON file of a different format and creates a data object that follows my schema definition. There are multiple places within my application where I modify the data object like this.

My current approach involves me creating an empty data object and a function to modify it at the top level of my application:
const [data, setData] = useState<MyDataType>();

and then passing the setData throughout my application to any component that requires it. This works fine in a few cases but having recently read about contexts in React I suspect that perhaps it’s not the best way to do things.
My approach to updating data is also inconsistent in that I use the method mentioned above in my custom non json forms components but in my customised JSON forms controls/renderers etc I make use of the addItems, removeItems functions that are provided.

is there a best practise for updating data outside of the controls?

Best regards,
James

Hi @james-morris,

what you describe sounds perfectly normal.

This works fine in a few cases but having recently read about contexts in React I suspect that perhaps it’s not the best way to do things.

I would recommend contexts once you notice that you add data, setData to various components only to pass them down a few levels. Then contexts can really help to not pollute your components with too many unrelated props.

The other use case is if you need access to some “extra” data within your custom JSON Forms renderers which you don’t want to make part of the data which JSON Forms manages. Then you can inject the “extra” data via React contexts into your renderers.

My approach to updating data is also inconsistent in that I use the method mentioned above in my custom non json forms components but in my customised JSON forms controls/renderers etc I make use of the addItems, removeItems functions that are provided.

Sounds fine. Within custom JSON Forms renderers I would always update the JSON Forms related data via the usual JSON Forms mechanisms, e.g. handleChange. Outside of JSON Forms you should use the standard of your app.

is there a best practise for updating data outside of the controls?

What you do sounds good from what you described. If you cover multiple use cases with your useState/setData you could think about using a useReducer instead. Then you could potentially decouple UI and update logic in a straightforward and natural way.

Cheers

1 Like