NuxtN
Nuxt2y ago
5 replies
jd

Best practices for state/composable to depend on fetched data?

I have a useUser composable that fetches API data to build the user: userInfo and companyInfo.

I get the error that a composable is used outside the Nuxt instance.

I want to know the best practices for implementing something like this, if anyone knows enough to help

Here's the code for the user composable and the user plugin.

composables/useUser.js 
export const useUser = async () => {
    async function refresh() {
        const authUser = useSupabaseUser()

        const { data: userInfo, error: userError } = await useFetch(
            `/user/${authUser.value.id}`,
        )

        const { data: company, error: companyError } = await useFetch(
            `/company/${userInfo.value.company_id}`,
        )

        return { ...userInfo.value, company: company.value }
    }

    const fetchedUser = await refresh()
    const user = useState('user', () => fetchedUser)

    return { user, refresh }
}


plugins/user-plugin.js
export default defineNuxtPlugin((nuxtApp) => {
    const { user, refresh } = useUser()
    console.log('user-plugin', user)
})
Was this page helpful?