Search code examples
reactjsreduxreact-reduxredux-thunkredux-toolkit

How to debounce createAsyncThunk from Redux Toolkit


I am migrating over from Redux to Redux Toolkit. The simplified code I have here is for debounced update using lodash/debounce.

import debounce from "lodash/debounce";

const updateApplication = async (app, dispatch) => {
const state = getState();

try {
  const result = await update(app);
  dispatch({
    type: UPDATE,
    result: result
  });
    } catch (err) {
    console.log(err);
    }
  };

export default debounce(updateThunk, 2000);

The problem is when I move over to createAsyncThunk it does not get executed.


const updateApp = createAction("app/update");
const updateApplication = createAsyncThunk(
  "app/updateDebounced",
  async (app, { dispatch }) => {
   
    try {
      const result = await update(app);
          dispatch(updateApp(result))
        );
      }
    } catch (err) {
      // console.log(err);
    }
  }
);

export default debounce(updateApplication, 2000)

How do I make it work?


Solution

  • const updateApp = createAction("app/update");
    const handler = async (app, { dispatch }) => {
        try {
          const result = await update(app);
    
          dispatch(updateApp(result));
        } catch (err) {
          // console.log(err);
        }
    }
    const debouncedHandler = debounce(handler, 2000);
    
    export default createAsyncThunk(
      "app/updateDebounced",
      debouncedHandler
    );