Skip to content

Best way to update related state fields with split reducers? #946

@gdborton

Description

@gdborton

I'm trying to work out the ideal way to update several top level fields on my state tree while still maintaining split reducers.

Here's a simple solution that I've come up with.

var state = {
  fileOrder: [0],
  files: {
    0:{
      id: 0,
      name: 'asdf'
    }
  }
};

function handleAddFile(state, action) {
  return {...state, ...{[action.id]:{id: action.id, name: action.name}}};
};

function addFileOrder(state, action) {
  return [...state, action.id];
}

// Adding a file should create a new file, and add its id to the fileOrder array.
function addFile(state, action) {
  let id = Math.max.apply(this, Object.keys(state.files)) + 1;
  return {
    ...state,
    fileOrder: addFileOrder(state.fileOrder, {id}),
    files: handleAddFile(state.files, {id, name: action.name})
  };
}

Currently I'm able to dispatch a single action {type: ADD_FILE, fileName: 'x'}, then addFile creates an action internally to send to addFileOrder and addFile.

I'm curious if it is considered a better approach to do either of the below.

  1. Instead dispatch two actions, one to add a file, then get it's id and dispatch an ADD_TO_FILE_ORDER action with the id.
  2. OR Fire and action like {type: ADD_FILE, name: 'x', id: 1}, instead of allowing addFile to calculate the new id. This would allow me to use combineReducers and filter on action type.

This example is probably trivial, but my actual state tree is a bit more complicated, with each file being added also needing to be added to other entities.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions