Skip to content

Instantly share code, notes, and snippets.

@ImKubass
Created March 18, 2025 10:45
Show Gist options
  • Save ImKubass/3a810cc4c67813c8fd8b933e503fcfc5 to your computer and use it in GitHub Desktop.
Save ImKubass/3a810cc4c67813c8fd8b933e503fcfc5 to your computer and use it in GitHub Desktop.
let filterAbortController: AbortController | null = null
const responseSettings = {
method: "GET",
}
const filterProducts = async (page?: string) => {
// Abort the previous request if it exists
if (filterAbortController) {
filterAbortController.abort()
}
// Create a new AbortController for the current request
filterAbortController = new AbortController()
const {signal} = filterAbortController
section?.classList.add("--loading")
let removeLoading = true
try {
const response = await fetch("your-url", {...responseSettings, signal})
if (response.ok) {
const data = (await response.json()) as productsData
if (data.success) {
console.log("do your stuff with data")
}
}
} catch (error) {
if (error.name === "AbortError") {
console.log("Previous filterProducts request aborted.")
removeLoading = false
} else {
console.error("Error fetching products:", error)
}
} finally {
if (removeLoading) section?.classList.remove("--loading")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment