Answer a question

I'm knew in React-Redux and I'm constantly getting stuck in the same error again and again - "TypeError: state.items is not iterable" I tried all types of solutions but didn't succeed.

I have a simple app that has an input and 2 buttons - when the person clicks on the addItem button the input text gets added to my list in my global state and when he clicks the reset button - my list in my global state becomes empty. the problem- the addItem button works just fine until after the reset button is clicked-the reset button resets the state and then when i try adding an item again it shows the error. "TypeError: state.items is not iterable" Here is my code in my reducer-

function manageList(state = { items: [] }, action) {
    debugger
    switch (action.type) {
        case ADD_ITEM:
            return { items: [...state.items, action.payload] };
        case RESET_LIST:
            return { item: [...state.items, []] };
        default:
            return state
    }
}
export default manageList;

I thought maybe to change the RESET_LIST item to items but that disabled the reset button

import { ADD_ITEM, RESET_LIST, } from '../actions'

function manageList(state = { items: [] }, action) {
    debugger
    switch (action.type) {
        case ADD_ITEM:
            return { items: [...state.items, action.payload] };
        case RESET_LIST:
            return { items: [...state.items, []] };
        default:
            return state
    }
}
export default manageList;

Answers

You have a typo there item instead of items. Also, it should be

case RESET_LIST:
            return { items: [] };

In general: the style of redux you are writing here is not the style of redux we are recommending people to learn if they learn redux nowadays, as redux has changed a lot over the last 1-2 years. You might be following an outdated tutorial. Please follow the official redux tutorials at https://redux.js.org/tutorials/index which will show you a lot more up-to-date approach that will lead to a lot less boilerplate and does not require you to work with immutable logic.

Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐