skip to content
Alvin Lucillo

Abort signal with resource

/ 1 min read

From yesterday’s journal, we learned that with resource, we can perform API calls asynchronously when resource detects we changed the request parameter. This is because we’re using signal of type string as the query parameter. However, if you will notice, when you enter values in the input field, the API calls are made sequentially based on the characters entered. When you look at the network tab, all API calls are performed until the last character is entered. This is unnecessary, and we need to abort those calls.

In the code below, what changed is the abortSignal being provided in fetch. This way, previous searches are aborted, ensuring only the most recent request is completed and avoiding unnecessary API calls that can affect app’s performance.

posts = resource<
	Post[],
	{
		query: string;
	}
>({
	request: () => ({
		query: this.query(),
	}),
	loader: async ({ request, abortSignal }) => {
		const response = await fetch(`https://dummyjson.com/posts/search?q=${request.query}`, {
			signal: abortSignal,
		});
		const json = await response.json();
		return json.posts;
	},
});