Reputation: 19
I am using Reacts useReducer hook. I am trying to increment +1 or -1 depending on which button on react is pushed. I am looking to assign the value before I return the value so I can POST the value to a database. When I run the code it increments by 1 on 0-1, but after that it increments by two. I tried console.log to view the value change and it only ran the console.log one time but ran the increment assignment twice. How do I run the value assignment only one time inside the case before returning the object. It also runs the POST request for each value change, ( 2 times)
const reducer = (state, action) => {
switch (action.type) {
case "increment":{
state.count = state.count +1;
console.log("Inside Reducer, state.count", state.count);
postFourthButtonClick(state.count)
return { count: state.count}
}
case "decrement":{
state.count -=1;
console.log("Inside decrement part of reducer, state.count:", state.count);
postFourthButtonClick(state.count);
return {count: state.count}
}
default:
throw new Error();
}
Upvotes: 1
Views: 122
Reputation: 3733
You shouldn't really perform side-effects (like making API requests) inside the reducer function. Side-effects belong inside a useEffect
hook.
What you want to do is probably along the lines of:
const reducer = (state, action) => {
switch (action.type) {
case "increment": {
return { count: state.count + 1 };
}
case "decrement": {
return { count: state.count - 1 };
}
default:
throw new Error();
}
};
You will have a useEffect
hook that calls your api.
By default, useEffect
runs both after the first render and after every update. If you want it to be re-run every time a certain value changes, you can put that value in the dependencies array.
useEffect(()=>{
makeSideEffect()
}, [valueThatDecidesWhenToRerun])
Upvotes: 1