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

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

    I've implemented a small deviation of a generic reducer which can be found over the internet. It is capable of deleting items from cache. All you have to do is make sure that on each delete you send an action with deleted field:

    export default (state = entities, action) => {
        if (action.response && action.response.entities)
            state = merge(state, action.response.entities)
    
        if (action.deleted) {
            state = {...state}
    
            Object.keys(action.deleted).forEach(entity => {
                let deleted = action.deleted[entity]
    
                state[entity] = Object.keys(state[entity]).filter(key => !deleted.includes(key))
                    .reduce((p, id) => ({...p, [id]: state[entity][id]}), {})
            })
        }
    
        return state
    }
    

    usage example in action code:

    await AlarmApi.remove(alarmId)
    
    dispatch({
        type: 'ALARM_DELETED',
        alarmId,
        deleted: {alarms: [alarmId]},
    })
    

提交回复
热议问题