Reputation: 958
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...
Upvotes: 3
Views: 3132
Reputation: 67567
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} };
}
}
}
})
Upvotes: 7