How do you add/remove to a redux store generated with normalizr?

前端 未结 5 1740
执笔经年
执笔经年 2021-01-30 00:02

Looking the examples from the README:

Given the \"bad\" structure:

[{
  id: 1,
  title: \'Some Article\',
  author: {
    id: 1,
    name: \'Dan\'
  }
},         


        
5条回答
  •  半阙折子戏
    2021-01-30 00:53

    Most of the time I use normalizr for data which I get from an API, because I don't have any control over the (usually) deep nested data structures. Let's differentiate Entities and Result and their usage.

    Entities

    All the pure data is in the entities object after it has been normalized (in your case articles and users). I would recommend either to use a reducer for all entities or a reducer for each entity type. The entity reducer(s) should be responsible to keep your (server) data in sync and to have a single source of truth.

    const initialState = {
      articleEntities: {},
      userEntities: {},
    };
    

    Result

    The results are only references to your entities. Imagine the following scenario: (1) You fetch from an API recommended articles with ids: ['1', '2']. You save the entities in your article entity reducer. (2) Now you fetch all articles written by a specific author with id: 'X'. Again you sync the articles in the article entity reducer. The article entity reducer is the single source of truth for all your article data - thats it. Now you want to have another place to differentiate the articles ((1) recommended articles and (2) articles by author X). You can easily keep these in another use case specific reducer. The state of that reducer might look like this:

    const state = {
      recommended: ['1', '2' ],
      articlesByAuthor: {
        X: ['2'],
      },
    };
    

    Now you can easily see that the article by author X is a recommended article as well. But you keep only one single source of truth in your article entity reducer.

    In your component you can simply map entities + recommended /articlesByAuthor to present the entity.

    Disclaimer: I can recommend a blog post I wrote, which shows how a real world app uses normalizr to prevent problems in state management: Redux Normalizr: Improve your State Management

提交回复
热议问题