Next.js Discord

Discord Forum

'use cache' long timeout and errors

Unanswered
Greater Swiss Mountain Dog posted this in #help-forum
Open in Discord
Greater Swiss Mountain DogOP
Hello. I'm trying to set up a function to wrap API calls in order to cache them. If an error occurs when fetching, I don't want to cache that response and would prefer that the request is retried the next time it is required. I've tried a few strategies, here's what I have currently:

async function withCache<T>(promise: Promise<ApiResponse<T>>, tags: string[]): Promise<ApiResponse<T> | undefined> {
    'use cache'
    cacheTag(...tags)
    cacheLife('minutes')
    const res = await promise
    console.log('cache miss')
    if (res.error !== undefined) {
        throw new Error(res.error)
    }
    return res
}
async function fetchData<T>(promise: Promise<ApiResponse<T>>, tags: string[]): Promise<ApiResponse<T>> {
    try {
        const cachedResult = await withCache(promise, tags)
        if (cachedResult === undefined) throw new Error('No response received from server.')
        return cachedResult
    } catch (error) {
        return { data: {} as Empty<T>, error: error instanceof Error ? error.message : 'An unknown error occurred.' }
    }
}


This results in two issues. First, while the page loads quickly, there's a second request that takes around a minute to time out. Additionally, there's occasionally a very verbose error:

 ✓ Compiled /organizations in 59ms
cache miss
 Cache  cache miss
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem.
[repeated several times]
 GET /organizations 200 in 25918ms
 GET /organizations 200 in 42524ms


I'd be grateful for any assistance on this pattern.

0 Replies