Skip to content

Instantly share code, notes, and snippets.

@spencerfeng
Last active July 25, 2022 12:17
Show Gist options
  • Save spencerfeng/384760a4cb8561f8283aeff1a29d0c9c to your computer and use it in GitHub Desktop.
Save spencerfeng/384760a4cb8561f8283aeff1a29d0c9c to your computer and use it in GitHub Desktop.
For tutorial: Create an abortable API using AbortController and AbortSignal
// This is a redux action creator
const searchItems =
(searchString: string, signal: AbortSignal) => async (dispatch) => {
dispatch(searchStarted());
try {
const items = await abortableSearchItems(searchString, signal);
dispatch(searchSucceeded(items));
} catch (error) {
if ((error as any).message === 'searchAborted') {
dispatch(searchAborted());
}
dispatch(
searchFailed(
error.message || "search failed for an unknown reason"
)
);
}
};
// Create an AbortController
const abortSearchController = new AbortController();
const signal = abortSearchController.signal;
// Dispatch the searchItems action
dispatch(searchItems(searchString, signal));
// When we want to abort the search
abortSearchController.abort();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment