useFetch in Nuxt 3: The Proper Way

By admin
I have recently seen

at least 2
CARDINAL

people make a wrapper around

useFetch
PERSON

in Nuxt 3 incorrectly by trying to call

useFetch
PERSON

as though it were fetch . While the approach they take will usually work (in general), it will very quickly cause you to have multiple errors and weird side effects.

Generally, the example i have seen is something like this:

export const useDataThing = ( ) => { const dataThing = useGlobalDataThing ( ) ; const dataThingId = useGlobalDataThingId ( ) ; const isPending = ref ( ) ; async function fetchDataThing ( ) { const { data , pending } = await

useFetch
PERSON

( ` api/dataThing/ ${ dataThingId . value } ` ) ; console . log ( pending . value ) ; isPending . value = pending . value ; dataThing . value = data . value ; } if ( ! dataThing . value ) { fetchDataThing ( ) ; } return { dataThing , dataThingId , fetchDataThing , isPending , } ; } ;

There is a whole bunch of bad errors you’re gonna get from this, mostly stemming from the fact that you’re not calling

useFetch
PERSON

in the root of your composable function. So let’s fix that.

A Better Way

useFetch is a composable and should be called in essentially the context of the setup method. It provides a way to trigger fetch calls.

Let’s rewrite this in a better way.

export const useDataThing = async ( ) => { const dataThing = useGlobalDataThing ( ) ; const dataThingId = useGlobalDataThingId ( ) ; const { data , pending : isPending , refesh , execute , … theRest } = await

useFetch
PERSON

( ( ) => ` api/dataThing/ ${ dataThingId . value } ` , { immediate : false , key : "getDataThingById" } ) ; async function fetchDataThing ( … args ) { await refresh ( … args ) ; dataThing . value = data . value ; } if ( ! dataThing . value ) { await

fetchDataThing
LOC

( ) ; } return { dataThing , dataThingId , fetchDataThing , isPending , … theRest } ; } ;

Doing it this way will Make it way more consistent for you. You can now fetch a different piece of data by doing:

const { dataThing , dataThingId , fetchDataThing } = await useDataThing ( ) ; dataThingId . value =

10
CARDINAL

; await

fetchDataThing
LOC

( ) ; console . log ( datathing . value ) ;

Hopefully this will save others with a lot of pain.