2

I'm building a react+redux app and i have an hard time deciding where to generate uid for my data.

To simplify things I'll explain my issue using the classic todo app example (my app is way more complex than this).

I currently have reducers for addTodo, selectTodos, updateSelectedTodos, and deleteSelectedTodos

I'm generating uid in my react component just before dispatching the addTodo action.

selectTodos stores the selected uid in the state.

updateSelectedTodos and deleteSelectedTodos will update/delete the todos listed in the "selected" list in state.

Now I need to add a new action "duplicateSelectedTodo" and I'm not sure of the best way to do it. I'd need to generate new uid for the duplicates. As I cannot do that directly in the reducer here's the solution I'm thinking of : - retrieve selected ids in my components, generate new ids and dispatch duplicate with an array of new ids - same but with all the data for the todo (might be a lot a data) - write an 'addUid' middleware which would trigger first in line and generate uid for all actions which needs some uid.

Any advice would be welcome :)

ps : generating uid in the component as I do now doesn't feels right to me...

Edwin Joassart
  • 930
  • 1
  • 7
  • 19

1 Answers1

6

You should generate IDs during the process of creating an action.

If you're writing the action creator by hand, it might be:

const addTodo = (text) => {
  const id = uuid();
  return {type: "todos/addTodo", payload: {text, id}}
}

If you're using Redux Toolkit's createSlice API (which I would strongly recommend), it would look like:

const todosSlice = createSlice({
  name: "todos",
  initialState: [],
  reducers: {
    addTodo: {
      reducer(state, action) {
        state.push(action.payload);
      },
      prepare(text) {
        const id = uuid();
        return { payload: {text, id} };
      }
    }

  }
})
markerikson
  • 63,178
  • 10
  • 141
  • 157
  • I do use redux toolkit and createSlice :) That's awesome, thanks! Even if i almost read the docs cover to cover, i still didn't catch that one. It's like the doc writer assume you're already an expert with Redux and are switching to toolkit. :( – Edwin Joassart May 22 '20 at 18:56
  • 1
    Actually, yes, that _is_ how the RTK docs are currently written - they assume you _are_ familiar with how to use Redux by hand already and focus on the differences when using RTK. The current docs talk about "prepare callbacks" in the [Intermediate Tutorial](https://redux-toolkit.js.org/tutorials/intermediate-tutorial#implementing-todo-ids), as well as [the `createSlice` API reference](https://redux-toolkit.js.org/api/createSlice#customizing-generated-action-creators). – markerikson May 23 '20 at 19:43
  • note: nanoid is included with redux toolkit – Mke Spa Guy May 28 '23 at 12:06