Next.js Discord

Discord Forum

Is my fetching implementation correct?

Unanswered
Irish Setter posted this in #help-forum
Open in Discord
Irish SetterOP
Is there anything wrong with my fetch utility code? It doesn't seem to refresh the data. I have set the REVALIDATE_TIME on my .env file which is currently 3600. I wanted to make sure that the new data actually contains data since it gets rate limited sometimes and gives back empty arrays which is why I wanted to keep the old cache as a backup and use it whenever this is the case. I am not sure if I am implementing it correctly

let cache = null;

export async function fetchAPI(apiUrl) {
    let response;
    let data;
    let attempts = 0;
    let revalidateTime = process.env.REVALIDATE_TIME

    while (attempts < 3) {
        response = await fetch(process.env.NEWS_API + apiUrl, {
            next: {
                revalidate: revalidateTime
            }
        })

        if (!response.ok) {
            throw new Error(response.statusText)
        } 

        data = await response.json()

        // Check if the data contains only empty arrays
        const isEmpty = Object.values(data).every(value => Array.isArray(value) && value.length === 0);

        if (!isEmpty) {
            // If the data is not empty, cache it and return it
            cache = data;
            return data;
        }

        // If the data is empty and there's cached data, return the cached data
        if (cache) {
            console.log("serving cached data new data is empty")
            return cache;
        }

        // If the data is empty and there's no cached data, wait for 1000ms before the next attempt
        await new Promise(resolve => setTimeout(resolve, 1000));
        attempts++;
    }

    // If there's no cached data after 3 attempts, throw an error
    throw new Error("Data is empty and there's no cached data after 3 attempts");
}

1 Reply

I haven't encountered such a problem where I'd have to do this, but isn't the cache variable created everytime that you make a api call?