Most applications work with data that has a nested structure. For example, blog posts have an author and comments. Comments also have authors and can get likes:
const blogPosts = [
{
id: 'post1',
author: { username: 'user1', name: 'User 1' },
body: '......',
comments: [
{
id: 'comment1',
author: { username: 'user2', name: 'User 2' },
comment: '.....'
},
{
id: 'comment2',
author: { username: 'user3', name: 'User 3' },
comment: '.....'
}
]
},
];
It is hard to work directly with such a structure for several reasons:
- It duplicates data inside it, so it is hard to update
- The logic of reducers gets more complicated the more nesting there is
The correct approach to Redux is to consider it as a relational database. The data inside the repository should be normalized. With this view, we can perceive each slice working with a set of entities as a separate table in the database.
Let's observe the basic principles of organizing data:
- Each entity should be stored in its reducer
- A collection of entities of the same type should be stored as an object, where the keys are object identifiers and the values are the objects themselves
- The order of data in this object should be defined by a separate array consisting only of identifiers
- Data should refer to each other only by identifiers
Now we will discuss that code example:
{
posts: {
entities: {
post1: {
id: 'post1',
author: 'user1',
body: '......',
comments: ['comment1', 'comment2'],
},
post2: {
id: 'post2',
author: 'user2',
body: '......',
comments: [],
},
},
ids: ['post1', 'post2'],
},
comments: {
entities: {
comment1: {
id: 'comment1',
author: 'user2',
comment: '.....',
},
comment2: {
id: 'comment2',
author: 'user3',
comment: '.....',
},
},
ids: ['comment1', 'comment2'],
},
users: {
entities: {
user1: {
id: 'user1',
username: 'user1',
name: 'User 1',
},
user2: {
id: 'user2',
username: 'user2',
name: 'User 2',
},
user3: {
id: 'user3',
username: 'user3',
name: 'User 3',
},
},
ids: ['user1', 'user2', 'user3'],
}
}
The data are now normalized. We store each entity in its reducer. The entities
object stores the entities themselves, and the ids
object has the identifiers. What advantages have we gained:
- The data aren't repeated, so if you want to make a change, you only need to do so in one place
- Reducers are not nested
- Data in this form are easy to retrieve and modify
Now let's see what it looks like inside the slices:
const slice = createSlice({
name: 'users',
initialState: {
ids: [],
entities: {},
},
reducers: {
addUser(state, action) {
const { user } = action.payload;
state.entities[user.id] = user;
state.ids.push(user.id);
},
removeUser(state, action) {
const { userId } = action.payload;
delete state.entities[userId];
state.ids = state.ids.filter((id) => id !== userId);
},
updateUser(state, action) {
const { userId, data } = action.payload;
Object.assign(state.entities[userId], data);
}
},
});
dispatch(addUser({ user }));
dispatch(removeUser({ userId }));
dispatch(updateUser({ userId, data }));
normalizr
The data coming from the back end isn't usually normalized, as it is convenient for the front end. Therefore, before adding them to the store, we must normalize them first. We can do it either by manually traversing the collection and converting it to the desired object or by using the normalizr library.
Recommended materials
Are there any more questions? Ask them in the Discussion section.
The Hexlet support team or other students will answer you.
- Article “How to Learn and Cope with Negative Thoughts“
- Article “Learning Traps“
- Article “Complex and simple programming tasks“
For full access to the course you need a professional subscription.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.