Lionel T
Lionel T

Reputation: 1597

Loop to dispatch a reducer in Redux

I have a json file with an array of Todos that I want to render as an initial state calling my reducer type: 'ADD_TODO'. Where is better to loop to dispatch the action:

Is better to loop in the Component, adding each single Todo, like:

myInitialTodos.forEach(
  (todo, id) => store.dispatch({
    type: 'ADD_TODO',
    id
  })
)

or in another reducer composed with ADD_TODO, like:

store.dispatch({
  type: 'ADD_TODOS',
  todos: myInitialTodos
})

In both cases, launching when componentDidMount (for example).

Maybe (and most probably) there is another and better way.

Thanks,

Upvotes: 0

Views: 6036

Answers (1)

Aaron
Aaron

Reputation: 39

Its definitely better to add separate action type of ADD_TODOS and pass an array of todos to your reducer. If you think about eventually adding a backend to your react application, you wouldn't want to make a bunch of API calls to add multiple todos, you'd want to send only one network request.

EDIT: Also, if you are always going to want to add the same list of todos to your application to start, the better way is to put them in the initial state that you pass to your reducer, so something like this could do the trick:

const initialState = [{title: 'A sample todo', completed: false},{title: 'Another sample todo', completed: false}]

const todos = (state = initialState, action) => { //Reducer logic }

Upvotes: 2

Related Questions