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 };
}
The package react-redux contains the bindings to run a Redux store in a React project. You’ll use code from react-redux to send actions from your components and to pull data from the store into your components. Use npm to install the two packages with the following command:
The package react-redux contains the bindings to run a Redux store in a React project. You’ll use code from react-redux to send actions from your components and to pull data from the store into your components. Use npm to install the two packages with the following command: When the component is finished installing, you’ll receive output like this.
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.
The store is your central collection of data. In the next step, you’ll learn to create reducers that will set the default values and update your store, but for now you will hard-code the data. Import the createStore function from redux, then pass a function that returns an object.
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;
}
}
I think you should spread them as "state.items" not as just "state".
Like this:
item: [...state.items,[]]
Not like this:
item: [...state,[]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With