Home > Software engineering >  store does not have valid reducer when trying to create multiple states in React Toolkit
store does not have valid reducer when trying to create multiple states in React Toolkit

Time:12-16

In my slice.js file, I have my slices:

import {createSlice} from "@reduxjs/toolkit";
import { combineReducers } from "@reduxjs/toolkit";

export const counterSlice = createSlice({
    name:"trigger",
    initialState:{
        trigger:false
    },

    reducers:{
        flip: (state) =>{
            state.trigger = !state.trigger;
        },

    }

})

export const projectNameSlice = createSlice({
    name:"setName",
    initialState:{
        name: "project"
    },

    reducers:{
        setName: (state, action) =>{
            state.name = action.payload;
        }
    }
})

export const {flip} = counterSlice.actions;
export const {setName} = projectNameSlice.actions;

export default combineReducers({
    counterSlice:counterSlice.reducer,
    projectNameSlice: projectNameSlice.reducer
}) 

At the bottom, I used the combineReducer to export multiple slices, and in my store.js I have the following code:

import { configureStore } from "@reduxjs/toolkit";
import {counterSlice, projectNameSlice} from "./trigger";

export default configureStore({
    reducer:{
        trigger: counterSlice,
        projectName:projectNameSlice
        
    },
})

When I try to deconstruct the values of either reducers like this:

const {trigger} = useSelector((state) => state.trigger);
  const {myProj} = useSelector((state) => state.projectName);

I get the following error:

Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.

When I export only one reducer, it works fine, but when I add the second I get this error, I looked at threads of other people getting the same error, but the cause/solution in their case did not work for me.

CodePudding user response:

You don't need that combineReducers call, but you cannot put your slices into configureStore, but you have to put the slice reducers in:

import { configureStore } from "@reduxjs/toolkit";
import {counterSlice, projectNameSlice} from "./trigger";

export default configureStore({
    reducer:{
        trigger: counterSlice.reducer,
        projectName:projectNameSlice.reducer,
    },
})

CodePudding user response:

I think this is what you want

export default configureStore({
    reducer: combineReducers({
           trigger: counterSlice,
           projectName: projectNameSlice,
    })
})

https://redux.js.org/api/combinereducers

  • Related