0

In a React app, I got a state variable that's set to 0 at first.

const [amount, setAmount] = useState(0)

The functionality i'm looking for is to add/remover product in a redux store.

So if a user presses a "+" button, it will check if amount is now bigger than 0, and if so it'll dispatch an action to the store. But what I'm getting is that only after the second "+" press, when the value of amount is already 2, the action is actually dispatched. This is the code :

const handleAmount = action => {
    if (action === 'plus') {
      setAmount(currAmount => currAmount + 1)
      updateStore()
    }
  }

const updateStore = () => {
    if (amount >= 1) {
      dispatch(addToCart(product))
    }
  }

What am I missing?

2
  • 1
    Can you provide us with the code of your action and reducer? Commented Oct 18, 2020 at 12:52
  • Why don't you implement amount in redux also? setState applies changes only in the next render. Redux and useReducer on the other hand give you the current state once they have changed. Commented Oct 18, 2020 at 13:04

1 Answer 1

3

State is updated asynchronously, so when you call updateStore right after calling setAmount, state hasn't updated yet, so updateStore function sees the old value of amount.

When you click the second time, it works because now the updated value of amount will be 2 and the old value that updateStore function will use is 1, so the condition if (amount >= 1) evaluates to true and as a result the action is dispatched.

You can fix this problem using one of the following options:

  • Pass the new value of amount to updateStore function as an argument

  • Use the useEffect hook that executes whenever amount changes. Just move the code inside updateStore function inside useEffect hook and add amount in the dependency array of the useEffect hook.

    useEffect(() => {
       if (amount >= 1) {
          dispatch(addToCart(product))
       }
    }, [amount]);
    

    and remove the updateStore function, you don't need it if you use the useEffect hook.

Sign up to request clarification or add additional context in comments.

1 Comment

What logic should I put inside useEffect?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.