The problem is that the server response time may vary and sometimes the previous request arrives after the latest and affects the state. The problem is easy to solve with takeLatest, but I want to know if there are a way to do this with debounce.
import { SEARCH_ARTICLES } from "../constants";
import { setError, setSearchArticles } from "../actions";
import { put, call, debounce } from "redux-saga/effects";
import fetchAPI from "../../API/fetchAPI";
function* debounceSearch() {
yield debounce(500, SEARCH_ARTICLES, fetchData);
}
export function* fetchData(action) {
const { keyword } = action;
try {
const response = yield call(
fetchAPI,
`https://openlibrary.org/search.json?title=${keyword}&page=1`
);
yield put(setSearchArticles(response.data.docs));
} catch (e) {
yield put(setError(e.message));
}
}
export default debounceSearch;
For the cancelation I'm using this approach:
import axios, { CancelToken } from "axios";
import { CANCEL } from "redux-saga";
export default function fetchAPI(url) {
const source = CancelToken.source();
const request = axios.get(url, { cancelToken: source.token });
request[CANCEL] = () => source.cancel();
return request;
}