I am learning the redux toolkit and unfortunately, I have faced an error like Type Error but I failed to make a solution.
Create Counter Slice
const { createSlice } = require("@reduxjs/toolkit");
const initialState = {
count: 0,
};
const counterSlice = createSlice({
name: "counter",
initialState,
reducers: {
increment: (state, action) => state.count++,
decrement: (state, action) => state.count--,
},
});
module.exports = counterSlice.reducer;
module.exports.counterActions = counterSlice.reducer;
Configure Redux Store
const { configureStore } = require("@reduxjs/toolkit");
const counterReducer = require("../features/counter/counterSlice");
// Configure Store
const store = configureStore({
reducer: {
counter: counterReducer,
},
});
module.exports = store;
Dispatch the redux Store
const store = require("./src/rtk/store/store");
const counterActions = require("./src/rtk/features/counter/counterSlice");
console.log(store.getState());
// subscribe to state chnages
store.subscribe(() => {
console.log(store.getState());
});
// dispatch Actions
store.dispatch(counterActions.increment());
store.dispatch(counterActions.decrement());
Error What I have faced like
TypeError: counterActions.increment is not a function
as given below,
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
{ counter: { count: 0 } }
/media/imdad/Programming/MERN/Redux/Redux-Toolkit/rtkBasicSetup/app.js:12
store.dispatch(counterActions.increment());
^
TypeError: counterActions.increment is not a function
at Object.<anonymous> (/media/imdad/Programming/MERN/Redux/Redux-Toolkit/rtkBasicSetup/app.js:12:31)
at Module._compile (node:internal/modules/cjs/loader:1256:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
at Module.load (node:internal/modules/cjs/loader:1119:32)
at Module._load (node:internal/modules/cjs/loader:960:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47
Node.js v18.17.0
Can anyone please help me to solve this issue? The error is also given in the attached file please check it.
It looks like you didn't actually export the counterSlice
actions correctly.
module.exports.counterActions = counterSlice.reducer;
should be
module.exports.counterActions = counterSlice.actions;
I'm not very familiar with module exports, but I think the counterActions
are also incorrectly imported.
const counterActions = require("./src/rtk/features/counter/counterSlice");
should probably be
const { counterActions } = require("./src/rtk/features/counter/counterSlice");
counterActions.increment
should now correctly be a reference to the increment
action/reducer declared in the state slice.