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

3 messages · Page 1 of 1 (latest)

vocal narwhal
#

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());
stoic glacier
#

what do you think can be better here?
in other words what do you feel like is bad here?

vocal narwhal
#

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