Skip to content

Instantly share code, notes, and snippets.

@DSchau
Last active November 7, 2019 05:19
Show Gist options
  • Save DSchau/10122afd2a3713108b9ed2f40991bb74 to your computer and use it in GitHub Desktop.
Save DSchau/10122afd2a3713108b9ed2f40991bb74 to your computer and use it in GitHub Desktop.
Semi Resilient Network Request
// make sure you wrap this in a useEffect, componentDidMount, etc.
const safeFetch = (timeout = 10000) => {
return (...args) => {
// this is sorta "unsafe" in the sense that a slow connection could cause this timeout
// a safer way would be to tap into and investigate error codes for e.g. ad blocked resources
// but this gets the idea across
return Promise.race([
fetch(...args),
new Promise((resolve, reject) => setTimeout(() => reject(new Error('Ad blocked or something')), timeout) // this failed, short-circuit
])
}
}
safeFetch()('/whatever.json') // if blocked, will reject after 10 seconds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment