After combining my reducer using combineReducer, action is not dispatching

Viewed 382

This was my reducer file. everything works fine If I use this. https://gist.github.com/ashiqdev/9129d43c4397ff752f88739cc1f4309f

I want to split it into multiple file using combineReducer. but after splitting it, redux action is not dispatching.

This is my product reducer:

import { SET_PRODUCTS } from '../actionTypes';

const init = {
  products: [],
  keyword: '',
  cartItems: {},
};

const productReducer = (state = init, action) => {
  if (action.type === SET_PRODUCTS) {
    return {
      ...state,
      products: action.payload,
    };
  }
  return state;
};

export default productReducer;

and here I am combining it:

import { combineReducers } from 'redux';

import productReducer from './productReducer';
import cartItemReducer from './cartItemReducer';
import keywordReducer from './keyWordReducer';

const reducers = combineReducers({
  products: productReducer,
  keyword: keywordReducer,
  cartItems: cartItemReducer,
});

export default reducers;

what I am missing here?

2 Answers

You have given wrong initial state on productReducer. It should be a plain empty array. and you should return only the products array.. not the whole state.

const productReducer = (state = [], { type, payload }) => {
  if (type === SET_PRODUCTS) {
    return [...payload]
  }
  return state;
};

or if you dont want to change the productReducer, you have to consume the store variable using store.products.products.

const products = useSelector((state) => state.products.products)

It seems that there is a mistake in the reducer function

const productReducer = (state = init, action) => {
  if (action.type === SET_PRODUCTS) {
    // here you have to return the new state for `state.products` and not for `state`
    return {
      ...state,
      products: action.payload,
    };
  }
  return state;
};

Try this reducer instead

const productReducer = (state = [], action) => {
  if (action.type === SET_PRODUCTS) {
    return [...action.payload];
  }
  return state;
};
Related