Reputation: 109
So i just learned redux and tried to make a simple list with redux and react. but when i click on the button to add item to the list i got an error "state is not iterable"
here is my code
reducer
function manageList(state = { items: [] }, action) {
switch (action.type) {
case ADD_ITEM:
return { list: [...state, action.payload] };
case RESET_LIST:
return {
item: [...state, []],
};
default:
return state;
}
}
action
export const ADD_ITEM = "ADD_ITEM";
export const RESET_LIST = "RESET_LIST";
export function addItem(text) {
return { type: ADD_ITEM, payload: text };
}
export function resetList() {
return { type: RESET_LIST };
}
Upvotes: 8
Views: 39924
Reputation: 41
You should use item: [...state.items,[]]
Because you just want to change items from the state.
Upvotes: 0
Reputation: 11
export const commentReducer = (state = initialState, action) => {
switch (action.type) {
case COMMENT_REQUEST:
return {
...state,
loading: true,
};
case COMMENT_SUCCESS:
return {
...state,
comment: [...state.comment, action.payload],
};
case COMMENT_FAIL:
return { loading: false, error: action.payload };
default:
return state;
}
};
It works for me
Upvotes: 1
Reputation: 1
You're spreading an object inside an array, to fix that you should spread the items property inside an array:
function manageList(state = { items: [] }, action) {
switch (action.type) {
case ADD_ITEM:
return { list: [...state.items, action.payload] };
case RESET_LIST:
return {
items: [...state.items, []],
};
default:
return state;
}
}
I think also that you should replace list
and item
by items
:
function manageList(state = { items: [] }, action) {
switch (action.type) {
case ADD_ITEM:
return { items: [...state.items, action.payload] };
case RESET_LIST:
return {
items: [...state.items, []],
};
default:
return state;
}
}
Upvotes: 12
Reputation: 381
I think you should spread them as "state.items" not as just "state".
Like this:
item: [...state.items,[]]
Not like this:
item: [...state,[]]
Upvotes: 2