Redux-saga Debounce by key


情境:post data 到不同的 key,但使用相同的 API 和 action

import { cancel, delay, fork, take } from 'redux-saga/effects';

export default function* debouncePerKey({
    pattern,
    selector,
    timeout,
    preFn,
    callApi,
}) {
    const map = new Map();

    while (true) {
        const action = yield take(pattern);
        const key = selector(action);
        const existingTask = map.get(key);

        if (preFn) {
            yield preFn(action);
        }

        if (existingTask) {
            yield cancel(existingTask);
        }

        const newTask = yield fork(function* () {
            yield delay(timeout);
            map.delete(key);
            yield callApi(action);
        });

        map.set(key, newTask);
    }
}

加入 root saga

fork(() =>
    debouncePerKey({
        pattern: postExamAnswerRequest.type,
        selector: (action) => action.payload.payload.question_id,
        timeout: 500,
        preFn: updateAnswer,
        callApi: handlePostExamAnswerRequest,
    }),
)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *