i am trying to call a reducer function from another reducer function.
but i get error ‘redux.js:283 Uncaught Error: Reducers may not dispatch actions.’
this is my counter reducer:
const counterReducer = (state = initialState, action) => {
switch (action.type) {
case "INCREMENT":
console.log("increment counter",state)
store.dispatch({ type: "SIGN_IN", payload: 'new data' })
return state + 1;
case "DECREMENT":
return state.count - 1;
case "RESET":
return (state.count = 0 );
default:
return state.count;
}
};
this is my logger reducer:
const loggedReducer = (state=false, action) =>{
switch(action.type){
case 'SIGN_IN':
console.log("SIGN_IN")
return !state;
default:
return state;
}
}
im trying to dispatch "SIGN_IN" action from "INCREMENT" action.
is it possible or not?
>Solution :
In Redux, it’s generally not recommended for a reducer to directly dispatch actions. Reducers should be pure functions that take the current state and an action as input and return a new state based on the action’s type and payload.
The error you’re encountering, "Reducers may not dispatch actions," is a result of trying to dispatch an action directly within a reducer. Instead of dispatching actions from within a reducer, you should dispatch actions from your components or other parts of your application that interact with the store.
In your case, you want to dispatch the "SIGN_IN" action from the "INCREMENT" action. To achieve this, you can dispatch the "SIGN_IN" action in the component or function where you handle the "INCREMENT" action, not within the "counterReducer" itself. Here’s an example of how you can do this:
import { useDispatch } from 'react-redux';
const YourComponent = () => {
const dispatch = useDispatch();
const handleIncrement = () => {
// Dispatch the INCREMENT action
dispatch({ type: 'INCREMENT' });
// Dispatch the SIGN_IN action
dispatch({ type: 'SIGN_IN', payload: 'new data' });
};
return (
<button onClick={handleIncrement}>Increment</button>
);
};