calebeaires
calebeaires

Reputation: 2084

Nuxt 3 HTTP request on demand after rendering: a client-side fetch

Nuxt 3 has those amazing data fetching functions (ex.: useFetch), but I come out on a situation that I need to make request after the rendering time (ex.: calling from a button and send a search term).

As I far know, useFetch are not working on client-side, here is what I have trying to do

<template>

<button @click="goSearch()">Search</button>

</template>

setup() {
        const goSearch = async () => {
            const { data } = await useFetch('search', () => $fetch('/api/search'));
            console.log(data.value);
        };

        return { goSearch };
    },
}


Does nuxt3 offers a built in function to make http request on demand (client-side official http axios like)?

Upvotes: 1

Views: 3613

Answers (3)

Phong Nguyen
Phong Nguyen

Reputation: 41

You should use refresh or execute function provided by useFetch. Here is my suggestion:

A. In your template:

<template> 
 <button @click="refresh()">Search</button>
</template>

B. In your script:

setup() {
  const { data, refresh } = await useFetch('search', () => $fetch('/api/search'));
  return { data, refresh };
}

Docs: Nuxt Data Fetching

Upvotes: 0

cyril
cyril

Reputation: 1017

useFetch is the same as using $fetch, here why not simply use fetch already in your code ?

const { data } = await $fetch('/api/search' );

i think you code is simply no just youcan use useFetch even on client side but like that :

const { data } = await useFetch('/api/search')

Upvotes: 0

calebeaires
calebeaires

Reputation: 2084

$fetch should work. The problem were a small bug that is now fixed. If you are experiencing this bug, just upgrade nuxt/ohmyfetch lib

npx nuxi upgrade --force

More here: https://github.com/nuxt/framework/issues/2502#issuecomment-999783226

Upvotes: 1

Related Questions