0

In the Redux Todo example.

https://github.com/reactjs/redux/tree/master/examples/todomvc

How would you approach creating a "copy" functionality. Basically, adding a new todo using existent todo data (name of the todo).

I was wondering if this is done through the actions? or in the reducer? or does it have to do a CRUD backend response?

carkod
  • 1,844
  • 19
  • 32

1 Answers1

0

I would personally put the copy functionality in the reducer. This would still require a new action. Its type would be COPY_TODO and it would also have the id of the todo you want to copy.

The reducer would look something like this:

case COPY_TODO: {
  const todoToCopy = state.find(todo => todo.id === action.id);

  if (todoToCopy) {
    return [
      {
        ...todoToCopy,
        id: state.reduce((maxId, todo) => Math.max(todoToCopy.id, maxId), -1) + 1,
      },
      ...state
    ];
  }

  return state;
}

This finds the existing todo in the state, copies it and updates the id to 1 above the current highest id so it will be unique.

DonovanM
  • 1,174
  • 1
  • 12
  • 17