I have the following structure in my Redux store.
persons: {
1: {
name: "John",
},
2: {
name: "Erica",
}
};
// First way
companies: [{
name: "Google",
persons: [1, 2]
}];
// Second way
companies: [{
name: "Google",
persons: [{
1: {
name: "John",
},
2: {
name: "Erica",
}
}];
I want to show persons in a company however both of the practices I tried has some issues.
In First way
, each time I want to look at company.persons
attribute, I should also call persons[id]
to obtain person information.
In Second way
, each time I make a modification to the person object, I also have to update all the child objects on each parent and it can quickly become a mess.
Basically I want companies.persons[id]
to point to persons
attribute so I can do stuff like companies.persons[0].name
but keep the single source of truth.
Any ideas?
You should consider using a Normalizing State Shape for your store in redux.
Using this approach I would suggest you to use your first approach where I suppose you keep separate various entities, like persons and companies, and linkt theme together using an id.
// First way
persons: {
1: {
name: "John",
},
2: {
name: "Erica",
}
};
companies: [{
name: "Google",
persons: [1, 2]
}];
This type of question probably belongs at https://codereview.stackexchange.com/ .
With that said. My suggestion. Split it up into two reducers and combine them with combineReducer for a cleaner way. It makes more sence to have a single "updateable" (immutable) object as root.
My suggestion would then be:
companies: [{
name: "Google"
}];
persons: {
"Google": {
1: { name: "John" },
2: { name: "Erica" }
}
};
If you need a key, or else feel free to use array as persons. I have always though maps makes better state objects and Object.keys can be easily used to iterate through them later.
Or you can ofcouse use your "method no 1" with a array of keys if that fits your backend and data structure better.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.