ReactJS & Redux - TypeError: state.reduxCart is not iterable

368 Views Asked by At

I am trying to insert items in redux but when i click the button I get the following error :

TypeError: state.reduxCart is not iterable

My Reducer code :

const INITIAL_STATE = {
    reduxCart: [],
    reduxCartCounter: 0
}


export default (state = INITIAL_STATE, action) => {
    switch (action.type) {

        case 'ADDITEM':
            return {
                ...state,
                reduxCart: [action.payload , ...state.reduxCart]  // ERROR
            }

        case 'ADDCOUNTER':
            return ({
                ...state,
                reduxCartCounter: action.payload
            })

        default:
            return state;
    }

}

Here is my Store code :

import rootReducer from './reducer';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage'; 

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';

const persistConfig = {
    key: 'root',
    storage,
}


const persistedReducer = persistReducer(persistConfig, rootReducer);
const store = createStore(persistedReducer, applyMiddleware(thunk));
const persistor = persistStore(store);
export { store, persistor };

My Actions Code :

export function AddToReduxCart(item) {
    return dispatch => {
        dispatch({ type: 'ADDITEM', payload: item  })
    }
}

How to solve this issue ? Any help would be appreciated.

1

There are 1 best solutions below

4
On

On your actions file, in your addItem function you can use getState function. then concat the two of the arrays in your action and dispatch them as the payload.

should be something like this:

import store from '../store';

export function addItem(nextItem) {
  const currentReduxCart = store.getState().reduxCart.map(item => ({...item}));
  const payload = [nextItem , ...currentReduxCart];
  return {
    type: 'ADDITEM',
    payload: payload,
  }
}
const INITIAL_STATE = {
    reduxCart: [],
    reduxCartCounter: 0
}


export default (state = INITIAL_STATE, action) => {
    switch (action.type) {

        case 'ADDITEM':
            return {
                ...state,
                reduxCart: action.payload
            }

        case 'ADDCOUNTER':
            return ({
                ...state,
                reduxCartCounter: action.payload
            })

        default:
            return state;
    }

}

If you want to add your actions code I will be able to help You to adjust it for your code.