1

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();

}

  • 1
    You're mutating your state when you assign a new value to `state.count` explicitly before the return value. See the docs for an implementation of incrementation: [React: useReducer](https://reactjs.org/docs/hooks-reference.html#usereducer) – pilchard Apr 23 '21 at 21:38

1 Answers1

1

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])
Moe
  • 3,467
  • 1
  • 19
  • 25
  • I am trying to run a POST request inside the case of the switch statement, so that on each increment or decrement a POST is sent to the database. If I put the increment or decrement inside the return statement, then I won't be able to use the POST request with the updated value. – RocketMan89 Apr 23 '21 at 22:46
  • 1
    I made an edit to answer this particular point. I hope this answers your question – Moe Apr 26 '21 at 11:18