How to update a value of a nested object in a reducer? - redux

I have built my state like so
const list = {
categories: {
Professional: {
active: false,
names: [
{
id: 1,
name: "Golf",
active: false
},
{
id: 2,
name: "Ultimate Frisbee",
active: false
}
]
}}
In my action I have added an ID option so I would like to change the active status when the user clicks the option to do so
I am using Immutable JS though not married to it. I am wondering how I could target the id of the object and update its active status in a reducer? I am also open to feedback on how to better improve my state

This is very common thing, and, actually, quite daunting. As far as I know, there is no really good and well-adopted solution in plain JS. Initially, Object.assign approach was used:
return Object.assign({}, state, {
categories: Object.assign({}, state.categories, {
Professional: Object.assign({}, state.Professional, {
active: true
})
})
});
This is too straightforward and cumbersome, I admit it, but I have to say that we've built few big applications with this approaches, and except for number of characters it is not bad. Nowadays, the most popular approach is using Object spread:
return {
...state,
categories: {
...state.categories,
Professional: {
...state.categories.Professional,
active: true
}
}
}
The second approach is much more cleaner, so if you use plain JS, then it seems as a good choice.
In Immutable.js I have to admit it is easier, you just do the next
return state.updateIn(['categories', 'Professional'], x => x.set('active', true));
But it has it's own drawbacks and caveats, so it is better to think about it seriously before committing to it.
And your last question regarding improving the state – usually it is better not to have such deep nesting (separate your concerns, very often fields don't depend on each other – like active status can be separated to another object), but it is hard to say because of no knowledge of your domain. Also, it is considered as normal thing to normalize your data.

The Redux docs section on Structuring Reducers covers this. In particular, see the section on Immutable Update Patterns. The examples given are for plain JS objects and arrays, but the same approach applies - map() over the list, return the existing item for everything you don't want to update and return a new version for the one you do want to update.
Per the docs, also note that it's easier to update a specific item if your data is stored in a normalized structure, since you can look it up by ID directly. The "Structuring Reducers" section covers normalization as well.

Related

Updating normalised data without causing more re-renders outside of the state slice that has been updated

I have some normalised data (items) within my redux store:
{
items: {
index: ['a','b'],
dict: {
a: {
title: "red",
},
b: {
title: "car",
}
}
},
...
}
So, if I want to update anything within an item object, the reducer looks like this:
...
const itemsReducer = (state = initialState.items, action) => {
switch (action.type) {
case itemsActions.types.UPDATE_ITEM: {
return {
...state,
[action.payload.itemId]: {
title: action.payload.title,
}
}
}
default: return state;
}
};
But this technique creates a new object for items, which can cause unnecessary components to re-render, when really it should only cause components that subscribe to state changes of the individual object to re-render.
Is there any way to get around this?
That is how immutable updates are required to work - you must create copies of every level of nesting that needs to be updated.
In general, components should extract the smallest amount of data that they need from the store, to help minimize the chance of unnecessary re-renders. For example, most of the time a component probably shouldn't be reading the entire state.items slice.
FWIW, it looks like you're hand-writing your reducer logic. You should be using our official Redux Toolkit package to write your Redux logic in general. RTK also specifically has a createEntityAdapter API that will do most typical normalized state updates for you, so you don't have to write reducer logic by hand.
I'll also note that the recently released Reselect 4.1 version has new options you can use for customizing memoized selectors as well.

How can I update deeply nested object inside array?

Hello good people of the stack!
I am working on a react-redux application and I am trying to update a property on a deeply nested structure in my reducer. The data structure is as follows and I want to update the text property:
state = {
assessment: {
requirements: [
questions: [
{
text
}
]
]
}
}
so I have tried the following:
// reducer code...
return {
...state,
[assessmentId]: {
...state[assessmentId],
requirements: [
...state[assessmentId].requirements,
[requirementId]: [
...state[assessmentId].requirements[requirementsId],
questions: [
...state[assessmentId].requirements[requirementsId].questions,
[questionId]: {
text: action.payload.response.text
},
],
] ,
],
},
};
This is more pseudo code than actual code to remove complexity.
I do not see any change in redux dev tools so I am wondering if I have made a mistake the way I get the nested objects and array elements.
I was also curious about using combine reducers here. I asked a colleague and they suggested to use that but I am unsure how you would take that approach here. As always, any help is appreciated.
I recommend immer for deep state changes in your reducers.
It adds a little weight to your bundle, and you'll get better performance from using the spread operator, but if you can live with that it'll make your code easier to read and write.
import produce from "immer";
// reducer code...
return produce(state, draft => {
draft[assessmentId].requirements[requirementsId].questions[questionsIndex].text = action.payload.response.text;
});
I'd say your issue stems from questions being an array which will take a little more work to keep straight than object based state.
As it is you appear to be trying to set the question value as if questions was an object. Maybe you just need to drop the [questionId] syntax, eg
questions: [
...state[assessmentId].requirements[requirementsId].questions,
{ text: action.payload.response.text },
],
This will set the text object as a new item on the end of the array though.
Depending on what you need to do (ie what already exists in the array and whether you are trying to add or update) you'll want to have a read of:
https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns#inserting-and-removing-items-in-arrays
https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns#updating-an-item-in-an-array

How should I deep-duplicate state data in Redux?

I have several instances of state where I need to support actions that duplicate some slice of state. For example, my product is a survey builder, so when I duplicate a question, I'd also like to duplicate its answers, rather than have multiple questions pointing to the same answer instances.
The state is normalized:
questionsById: {
q01: {
...
answers: ["a01"],
...
}
}
answersById: {
a01: {...}
}
When dispatching an action of QUESTION_DUPLICATE, I'd like to also duplicate any answers. Currently my QUESTION_DUPLICATE action creator also creates a mapped list of new answer keys, and then the answer reducer consumes this.
This pattern seems unwieldy to me, especially when considering the possibility of deeper duplications (for example, duplicating a Page, which contains Questions, which contain Answers...). Is there a better pattern for deeply duplicating normalized data?
The answer may revolve around how you normally handle normalizing and denormalizing your data. For example, in my blog post Practical Redux, Part 8: Form Draft Data Management, I reuse my existing normalization logic (which leverages the redux-orm library) to copy an item to be edited between the "current" and "draft" slices in my state. So, similarly, one approach would be to denormalize the question you want to duplicate, and then re-normalize it (in either the action creator or the reducer, as you see fit).
I settled on using normalizr & I came up with a recursive duplicator function. It accepts an entity, schema, and keygen function, & recursively updates any nested entities based on the schemata by giving them new ids. In the base case (when there are no further nested entities) it will return the basic thing with its key updated.
const duplicator = (entity, schema, keygen) => {
const newEntity = {
...entity,
[schema._idAttribute]: keygen(entity, schema)
};
if (Object.keys(schema.schema).length === 0) {
return newEntity;
}
return Object.keys(schema.schema).reduce(
(acc, nestedKey) => {
if (!entity.hasOwnProperty(nestedKey)) {
return acc;
}
if (!Array.isArray(schema.schema[nestedKey])) {
return {
...acc,
[nestedKey]: duplicator(
entity[nestedKey],
schema.schema[nestedKey],
keygen
)
};
}
return {
...acc,
[nestedKey]: acc[nestedKey].map((nestedEntity, index) =>
duplicator(nestedEntity, schema.schema[nestedKey][0], keygen)
)
};
},
{ ...newEntity }
);
};
export default duplicator;
This currently doesn't support the schema.Array setup of normalizr for multiple entity types in an array. I'm not currently using schema.Array and this case would be pretty non-trivial to support, but I'll consider it in the future.

How to use normalized state in Redux?

I need help designing a simple app which allows user to rate videos using a form. My state is composed by 2 reducers, one that holds data about all ratable videos (in a normalized fashion) and another one that holds the form state:
{
videos: {
'video1Id': { id: 'video1Id', title: 'Cat video', duration: 120, ... },
'video2Id': { ... },
...
},
rateForm: {
'videoId': 'video1Id'
'userComment: 'A nice video about cat'
'formSubmitted': false
...
}
}
Note that, inside rateForm, I reference the video id instead of the video object. Problem is, how can I retreive the whole video object from my rateForm reducer ?
I feel like I'm following the best practice of Redux design but I'm stuck at this really simple use case. Any help appreciated.
Thanks
One thing to remember, reducer should be AS SIMPLE AS POSSIBLE. Only doing atomic operations on reducer level. From what I can tell you trying to retrieve the whole video object in your reducer just doesn't sound right.
Depending on your needs, usually, you don't need to fetch the whole video object if you just want to comment on it or rate it. But if you are 100% sure you have to, A good place to do this is in your action. Using Redux-Thunk, you will have access to the whole state object before you return your thunk. Example
function doSomethingToVideo (videoId, something) {
return (dispatch, getState) => {
const video = getState().videos[videoId]
// Do what ever
return somethingElse
}
}
Reference: Redux author's answer on a similar matter.
Accessing Redux state in an action creator?

Meteor - How do you exclude properties in a child collection from being published?

Imagine you have a collection similar to the following...
Tests = [
{
name: 'Some Test',
questions: [
{ question: 'Answer to life, the universe, and everything?', answer: '42' },
{ question: 'What is your favorite color?', answer: 'Blue' },
{ question: 'Airspeed velocity of unladen European Swallow?', answer: '24 mph' }
]
}
];
How do you publish the entire collection except for the answer property?
I understand you can do the following to omit properties from the publish...
Meteor.publish('tests', function() {
return Tests.find({}, {fields: {name:0}});
});
But I'm not sure how to omit a property from an array property.
Thanks!
It can't be done the way you want to do it. Meteor only supports field specifiers that are 1 level deep. You can sometimes get a sub-field specifier to work, but it's not reliable.
You can put your questions into their own collection with a testId field that links them back to the test, relational style. One question per document, and then you'll be able to specify that only the question field gets published.
Meteor.publish ('questions', function(testId) {
return Questions.find({testId: testId}, {fields: {question: 1}})
});
It's not ideal, but pretty painless compared to trying to find a workaround that allows your questions to live in the test document.
There might be a way to do this manually with a more involved publish. There's a similar question here with an answer that gets into it.

Resources