Reputation: 151
I am trying to write an app, where the user can add an item to the collection. The user types the name of collection-item and the item with this name occurs.
But when i dispatch action addCollection
:
export function addCollection(text) {
console.log("ACTION ADD COLLECTION FIRED");
return {
type: "ADD_COLLECTION",
text
}
}
to my reducer :
export default function collection(state = [], action) {
switch(action.type) {
case "ADD_COLLECTION":
return (
Object.assign({}, state, {
collections: [
{
name: action.text,
src:''
},
...state.collections
]
})
);
}
return state
}
ERROR OCCURED :
TypeError: Cannot convert undefined or null to object
It comes to line 6 in my reducer. I think reducer don't know my state.collection
var initialState = {
collections:[
{
name:"Aenean in justo ante",
src: ''
},
{
name:"Aenean in justo ante",
src: ''
}
],
formIsRender: false
}
const store = createStore(allReducers, initialState)
Where is the mistake?
Upvotes: 0
Views: 112
Reputation: 31024
Your initial state is an array
not an object
.
You can't and shouldn't use Object.assign
on arrays.
You can use though the spread operator in order to not mutate the array.
Try this instead:
case "ADD_COLLECTION":
return [...state, {name: action.text}]
Another thing i've noticed is that in your initial state object you named it collections
(plural) and your reducer's name is collection
(singular).
Make sure it's not a typo.
Upvotes: 3