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

前端 未结 5 1737
执笔经年
执笔经年 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:42

    Years late to the party, but here goes —

    You can easily manage normalized reducer state with no boilerplate by using normalized-reducer. You pass in a schema describing the relationships, and it gives you back the reducer, actions, and selectors to manage that slice of state.

    import makeNormalizedSlice from 'normalized-reducer';
    
    const schema = {
      user: {
        articles: {
          type: 'article', cardinality: 'many', reciprocal: 'author'
        }
      },
      article: {
        author: {
          type: 'user', cardinality: 'one', reciprocal: 'articles'
        }
      }
    };
    
    const {
      actionCreators,
      selectors,
      reducer,
      actionTypes,
      emptyState
    } = makeNormalizedSlice(schema);
    

    The actions allow you to do basic CRUD logic as well as more complex ones such as relational attachments/detachments, cascading deletion, and batch actions.

    Continuing the example, the state would look like:

    {
      "entities": {
        "user": {
          "1": { 
            "id": "1", 
            "name": "Dan",
            "articles": ["1", "2"]
          }
        },
        "article": {
          "1": { 
            "id": "1",
            "author": "1",
            "title": "Some Article",
          },
          "2": {
            "id": "2",
            "author": "1",
            "title": "Other Article",
          }
        }
      },
      "ids": {
        "user": ["1"],
        "article": ["1", "2"]
      }
    }
    

    Normalized Reducer also integrates with normalizr:

    import { normalize } from 'normalizr'
    import { fromNormalizr } from 'normalized-reducer'
    
    const denormalizedData = {...}
    const normalizrSchema = {...}
    
    const normalizedData = normalize(denormalizedData, normalizrSchema);
    const initialState = fromNormalizr(normalizedData);
    

    Another example of normalizr integration

提交回复
热议问题