Redux nested gearboxes or normalize condition?

I am creating a form component with React and want to save the form and field using Redux.

So, I have a form reducer and a formField reducer.

First, I monitored my gut feeling and tried to put the Form reducer in the form reducer. This basically meant the presence of cases related to the form, related to both the screen and the form reducer and formField reducer.

It seemed a bit messy (duplicate code), so I read more in the documentation and found out that it is recommended to normalize the state. So I took the nested formFields and placed them at the same level as the forms.

This made the gearbox nice and clean, but now getting the Fields form for a specific form seems awful. I basically iterate over all Forms Fields every time and return only those that have the correct formId parameter.

The Redux documentation states that you should treat the state as a normalized database, but didnโ€™t he forget that you donโ€™t have the luxury of being able to query the results?

Did I miss something? What is the recommended way to solve this problem?

+6
source share
2 answers

It looks like you are saving the formFields state as an array, but want to query it as an object with formId being the key:

This made the gearbox nice and clean, but now getting the Fields form for a specific form seems awful. I basically iterate over all Forms Fields every time and return only those that have the correct formId parameter.

If you change the state of formFields as an object, it will be much easier for you to request: formFields[fieldId] .

As noted in another answer, you can use to write compound โ€œselectorsโ€ that determine how to calculate the derived state . Then your component code will be simple, because all the heavy ups of data preparation are handled by small and compound selectors.

You can check gearboxes and selectors in shopping-cart to better understand how state is structured in Redux idiomatic applications. Please note that this example uses vanilla functions for selectors, but we recommend using Reselect for better performance.

+4
source

As I understand it, your problem is with the data request. (i.e. fields that belong to form X).

There is also a reselect utility, your use case seems to match what it solves.

You just need to write a selector waiting for formId , and it will return an array of form fields.

+1
source

All Articles