0

I've searched the answers for this question, but the answers are quite vague, and I still don't get it why we need Redux-Thunk instead of Promise to handle async flows.

Please help to take a look at one of my pieces of code below.

export default function CalculationPage() {
  const value = useSelector((state) => state.value);
  const dispatch = useDispatch();
  const handleIncreaseClick = () => {
    // This is a thunk
    const increaseValue = () => (dispatch) => {
      fetch().then(() => dispatch({ type: 'INCREMENT' }));
    };
    dispatch(increaseValue());
    // Why can't we use Promise directly? 
    // fetch().then(() => dispatch({ type: 'INCREMENT' }))
  };

  const handleDecreaseClick = () => {
    dispatch({ type: 'DECREMENT' });
  };
  return (
    <div>
      <span className='calculation_value'>value: {value}</span>
      <div>
        <button className='calculation_button' onClick={handleIncreaseClick}>
          Increase
        </button>
        <button className='calculation_button' onClick={handleDecreaseClick}>
          Decrease
        </button>
      </div>
    </div>
  );
}
  • 1
    `fetch().then(() => dispatch({ type: 'INCREMENT' }))` fires immediately, not on demand. – VLAZ May 28 '21 at 06:29
  • this might help https://redux.js.org/tutorials/fundamentals/part-6-async-logic#redux-middleware-and-side-effects – boxdox May 28 '21 at 06:30

0 Answers0