Last active
July 25, 2022 12:17
-
-
Save spencerfeng/384760a4cb8561f8283aeff1a29d0c9c to your computer and use it in GitHub Desktop.
For tutorial: Create an abortable API using AbortController and AbortSignal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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