Search code examples
reactjsreduxreact-redux

State undefined when using combineReducers()


I can't get my state when I want to combine my 2 reducers.

All was working when I was using only one reducer but when I tried with combineReducers(), I couldn't get my state anymore.

 const initialState = 
{ 
    films: []
}

const filmsReducer = (state = initialState, action) => {
    let nextState;

    switch (action.type)
    {
        [...]
        default:
            return state;
    }
}

export default filmsReducer;
const initialState = { checkedCategories: [''] }

const categoriesReducer = (state = initialState, action) => {
    let nextState;

    switch (action.type) {
        [...]
        default :
            return state;
    }
}

export default categoriesReducer;
import { combineReducers } from 'redux';

import films from './films-reducer';
import categories from './categories-reducer';

export default combineReducers({films, categories});
import { createStore } from 'redux';

import rootReducer from '../reducers/index';

export default createStore(rootReducer);

Below is where I get an undefined

import React, { useEffect, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';

export const Categories = (props) => {
    const [categories, setCategories] = useState([]);
    const checkedCategories = useSelector(state => state.checkedCategories)
    const dispatch = useDispatch();

    const categoryToggle = (category) => {
        console.log(checkedCategories);
        if (checkedCategories.findIndex(item => item.id === category.id) !== -1)
            return (<div>caca</div>)
    }
[...]
}

I got an initialState and a default return for both.


Solution

  • By adding combineReducers you've changed the structure of your state object.

    The structure was previously a single object containing checkedCategories. Something like this:

    state: {
      checkedCategories: ['']
    }
    

    But now its something like this:

    state: {
      films: {
        films: []
      }, 
      categories: {
        checkedCategories: ['']
      }
    }
    

    You need to adjust your selectors accordingly:

    const checkedCategories = useSelector(state => state.categories.checkedCategories)
    //                                                   ^ nested one level deeper now