c10b10 c10b10 - 2 months ago 6
React JSX Question

How does one properly manage delete of normalized data when different components rely on the same entity list?

Lets say you have:


  • a paginated list of all the books available in your app. You contain that in a
    BooksList
    component.

  • a list of the top books in your app in a
    TopBooksList
    component.

  • all this data that you fetch from a rest api gets normalized and saved in your Redux store, so your store looks something like this:

    {
    entities: {
    books: {
    1: { ... },
    2: { ... },
    3: { ... },
    4: { ... },
    5: { ... }
    }
    },
    topBooksList: [5, 2, 1],
    booksList: [1, 2, 3, 4, 5]
    }

  • A user deletes book
    5
    by clicking on the delete button on the book in the
    BooksList
    component



Each time a delete happens, the corresponding entity is deleted from the entities list, and from the results list of that component.

0. What is the best way to deal with the fact that there are other components on the page that reference that entity that was just deleted?

1. Do you try to coordinate components by adding switch statements for the delete action in every reducer that deals with that kind of data? 1.1 If so, what if you want always make sure to keep in sync a component that ends up affected by that delete, like the
TopBooksList
component in the example. By deleting book
5
, you end up a
topBooksList
of length
2
, what you need it to have a length of 3. Do you somehow mark it as dirty and refetch data? Doesn't this strategy get tedious when the number of related components on the page grows?

2. Is there a different, simpler strategy?

DDS DDS
Answer

You're supposed to add switch cases in every reducer that deals with the book. There you do what's necessary to keep everything in order (maintain referential integrity, make sure the top list is 3 long, etc).

However, if this involves fetching data from the backend then this should be placed in the async action creator for deleteBook.

The reason for that is that reducers should always be pure, which means they can't have side effects.

In your case I might have a longer topBooksList so threes no need to fetch each time a book is deleted. You do not need to display them all.

Doesn't this strategy get tedious when the number of related components on the page grows?

Yes it does get tedious. Try Redux-Orm or a Redux-Schema.