NuxtN
Nuxtβ€’15mo ago
AxelSorensen

UseAsyncData - undefined Ref

I am using vuefire to fetch data from firebase. I have been using useAsyncData inside of a custom composable to hide away my caching logic etc. This works fine for usecases where I only need to do one "useCollection" or "useDocument" call but now I need to fetch a document of episode Id's from by database and then immediatly fetch the actual episodes based on these:

I have tracked down the problem to the season_episodes being undefined when I first open the page where I call this composable (see code below) πŸ€”

Is there any way to make useAsyncData wait for this variable?πŸ™
// composables/useEpisodes.js
import { query, doc, collection, limit, orderBy, where, documentId } from 'firebase/firestore' // adjust the imports based on your setup

export async function useEpisodesFromSeason(seasonId: string, ep_limit: number, order: 'asc' | 'desc', key: string) {
    const db = useFirestore()
    const nuxt = useNuxtApp()
    const { data: episodes } = await useAsyncData(key, async () => {
        const seasonDocRef = doc(db, 'seasons', seasonId)
        const season_episodes = useDocument(seasonDocRef, { once: true })
        // season_episodes is undefined on the first page load and therefore the query below doesn't work

        const q = query(collection(db, 'episodes'), where(documentId(), 'in', season_episodes.value.data.episodes), limit(ep_limit), orderBy('date', order))
        return useCollection(q, { once: true, ssrKey: key })

    }, {

        transform: (data) => {
            return {
                data,
                fetchedAt: Date.now(),
            }
        },
        getCachedData: (key) => {
            const cachedData = nuxt.payload.data[key] || nuxt.static.data[key]
            if (!cachedData) {
                return
            }
            // if (Date.now() - cachedData.fetchedAt > 1000 * ) { // 1 minute cache
            //     return
            // }
            return cachedData
        }

    })

    return { episodes }
}
Screenshot_2024-10-23_at_01.29.41.png
Was this page helpful?