SamKirklandWA SamKirklandWA - 1 month ago 9
React JSX Question

React/Redux: state called twice? (concat(), not push())

I am having an issue with adding new

todo
to
todos
, classic one. Doing it on React/Redux.

Here's
reducer-todos.js
:

export default function (state=[
{
id: 0,
todo: "Study English"
},
{
id: 1,
todo: "Run sprint"
},
{
id: 2,
todo: "Call Bob"
}], action) {
switch(action.type) {
case "ADD_TODO":
return state.push({id: state.length, todo: action.todo});
break;
}
return state;
}


Here's the issue I get:

enter image description here

Somehow
todos
object becomes
4
, not Array[4]. Why is this happening?

Please let me know if additional info needed.

Answer

Somehow todos object becomes 4, not Array[4]. Why is this happening?

You're using push which will return its new size. Use concat instead which will return a new array with your new item added without mutating.

So this:

return state.push({id: state.length, todo: action.todo});

Should become:

return state.concat({id: state.length, todo: action.todo});
Comments