S
SolidJS23h ago
Angius

Preferred way of handling `429 Too Many Requests` with `createResource`?

I have an API that returns 429 with a retry-after header. The way I handle it right now seems... suboptimal to me. It works fine, don't get me wrong, but I have a feeling it culd be handled better.
const [canLoad, setCanLoad] = createSignal(true);

const loadQuote = async () => {
if (!canLoad()) {
return JSON.parse(window.localStorage.getItem("quote")) as QuoteDto;
}
setCanLoad(false);

const response = await getQuote();

setTimeout(
() => {
setCanLoad(true);
},
Number.parseInt(response.headers.get("retry-after")) * 1000,
);

if (response.ok) {
window.localStorage.setItem("quote", JSON.stringify(response.data));
return response.data;
}

if (response.status === 429) {
return JSON.parse(window.localStorage.getItem("quote")) as QuoteDto;
}
};

const [quote, { refetch }] = createResource<QuoteDto>(() => loadQuote());
const [canLoad, setCanLoad] = createSignal(true);

const loadQuote = async () => {
if (!canLoad()) {
return JSON.parse(window.localStorage.getItem("quote")) as QuoteDto;
}
setCanLoad(false);

const response = await getQuote();

setTimeout(
() => {
setCanLoad(true);
},
Number.parseInt(response.headers.get("retry-after")) * 1000,
);

if (response.ok) {
window.localStorage.setItem("quote", JSON.stringify(response.data));
return response.data;
}

if (response.status === 429) {
return JSON.parse(window.localStorage.getItem("quote")) as QuoteDto;
}
};

const [quote, { refetch }] = createResource<QuoteDto>(() => loadQuote());
3 Replies
zulu
zulu23h ago
what do you think can be better here? in other words what do you feel like is bad here?
Angius
AngiusOP23h ago
Not 100% sure to be honest. The fallback to localstorage irks me, since it could simply not update the current value if the request is throttled
zulu
zulu22h ago
yeah, I guess hiding the problem might be the 1st issue ( fallback to cache on error) might be acceptable in your use case 2nd issue, is that quote in LocalStorage might be empty there is no guarantee that this request was called before.

Did you find this page helpful?