S
SolidJS9mo ago
ish

Handling errors in createResource

My createResource handle fetches data from a REST API and is displayed on the screen. I have interval that calls refetch to refresh the data. If the fetch fails, my interval will keep running, and even if the remote service comes up, the refetch occurs, but the page never renders the new data. Is there a better way to handle errors in my resource? I don't want to try catch and return no data, as I want to display the existing data until new data can be retrieved.
4 Replies
deluksic
deluksic9mo ago
Note that you need to refresh error boundaries yourself, they will not rerender automatically See second arg to fallback https://docs.solidjs.com/reference/components/error-boundary
mdynnl
mdynnl9mo ago
it's probably simpler to manually handle the fetching
const [data, setData] = createSignal()

const defaultInterval = 5000
let interval = defaultInterval
setTimeout(async function load() {
try {
const res = await fetch('https://throwy.api')
res.ok && setData(await res.json())
interval = defaultInterval
} catch {
interval = interval * 1.5 // simple backoff
}
setTimeout(load, interval)
}, interval)
const [data, setData] = createSignal()

const defaultInterval = 5000
let interval = defaultInterval
setTimeout(async function load() {
try {
const res = await fetch('https://throwy.api')
res.ok && setData(await res.json())
interval = defaultInterval
} catch {
interval = interval * 1.5 // simple backoff
}
setTimeout(load, interval)
}, interval)
downsides: can't use suspense better yet
const lastKnownGoodData = createMemo((p) => {
try {
return res(); // resource errors only throw on read
} catch {
return p;
}
});
const lastKnownGoodData = createMemo((p) => {
try {
return res(); // resource errors only throw on read
} catch {
return p;
}
});
https://playground.solidjs.com/anonymous/91406f43-8def-4117-bb79-6786602052b5
ish
ish9mo ago
thanks, yeah.. Probably manually fetching, its what I was doing before. Also found taht checking .error before attempting to use the resource
mdynnl
mdynnl9mo ago
yeah, checking .error or .state === 'errored' also works
Want results from more Discord servers?
Add your server