1
votes

I am trying to get my head around using react and redux together. The Problem I have is, that it seems to me a lot of boilerplate code when the app gets complexer.

For example, take the Todo App from the redux documentation. Lets assume we want to extend the example, given a todo more properties:

  • A title
  • A due-date
  • A owner
  • more stuff

Now, I would add addtional Actions for modifying these properties:

const ADD_TODO = 'ADD_TODO'
const REMOVE_TODO = 'REMOVE_TODO'
const TOGGLE_TODO = 'TOGGLE_TODO'
const CHANGE_TITLE = 'CHANGE_TITLE'
const CHANGE_DUEDATE = 'CHANGE_DUEDATE'
const CHANGE_OWNER = 'CHANGE_OWNER'
... more stuff ...

Now the callbacks for Todo must be extended by:

  • onChangeTitle(title)
  • onChangeDueDate(dueData)
  • onChangeOwner(owner)
  • ...

And the callbacks for TodoList must also be extended:

  • onChangeTitle(index, title)
  • ...

Finally the top level component must subscribe to all these callbacks and dispatch the action.

That seems to be a lot of boilerplate, especially when the component hierarchy goes even deeper.

My initial Idea would be, that Todo has only one callback:

  • onChange(newData)

and TodoList:

  • onChangeTodo(index, newData)

But than newData must be created in Todo, which basicly means implementing something like the reducer there.

Am I getting the right Idea here? Can I reduce this?

1

1 Answers

1
votes

I'd do something like:

const TODO_PROPERTY_UPDATE = 'TODO_PROPERTY_UPDATE'

Which would be used for all properties of a TODO (title, duedate, owner, etc.)

Action:

export function updateTodoProperty(index, property, propertyValue) {
  return { type: TODO_PROPERTY_UPDATE, index, property, propertyValue }
}

In your reducer:

case TODO_PROPERTY_UPDATE:
  return state.map((todo, index) => {
    if (index === action.index) {
      return Object.assign({}, todo, {
        [action.property]: action.propertyValue
      })
    }
    return todo
  })