Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NUXT 3 fetching data on the client side

For example we have the posta api which can return posts (get) and create new ones (post).

First i am need to get them on the server side. I am do that on the asyncData option like that. I am use useFetch composible to prevent double data fetching by $fetch. https://nuxt.com/docs/api/utils/dollarfetch

Okey,i am have the post data getting by the server side. But now i am want to be able to add some data using methods options api.

Should my function to be async prefixed or that is unnessery if i would use it only on the client side? Which method should i use to post some data if i want to use the funtion only on the client side?

export default defineNuxtComponent({
   
    async asyncData () {
        return {
            posts: useFetch ('/api/posts')['data']
        }
    },

   methods:{
    post(event : Event) {
        event.preventDefault();

        // post form data to api

       $fetch('/api/posts',{
            method: 'POST',
            body: JSON.stringify(this.form)
        })
        // this.posts.push(data);

    
    },
}

Is using

 the $fetch('/api/posts',{
            method: 'POST',
            body: JSON.stringify(this.form)
        }) 

is the right way? How can i refresh posts on the client side after. Something like

axios.post().then(data)=>{this.posts.push(data)} 

In official docs https://nuxt.com/docs/getting-started/data-fetching says :

useFetch, useLazyFetch, useAsyncData and useLazyAsyncData only work during setup or Lifecycle Hooks

In the nuxt module site https://axios.nuxtjs.org/ says:

Axios module supports Nuxt 2. Nuxt 3 users can use the new isomorphic $fetch API (migration guide).

So should i use or not the $fetch , useFetch, useLazyFetch, useAsyncData and useLazyAsyncData during client side fetches or no?

I cant find any example in the nuxt3 docs to using fetch in the methods like clicking on buttons etc.

like image 351
Sergei Illarionov Avatar asked Oct 11 '25 10:10

Sergei Illarionov


1 Answers

Here's an example of how your component might look like:

<template>
  <div>
    <input v-model="form.searchTerm" />
    <input v-model.number="form.pageSize" type="number" />
    <button @click="getPosts">Get posts</button>
  </div>
  <template v-if="posts.length">
    <div v-for="post in posts" :key="post.id">
      <pre v-text="JSON.stringify(post, null, 2)" />
    </div>
  </template>
</template>
<script setup>
const posts = ref([])

const form = reactive({
  searchTerm: '',
  pageSize: 25
})

const getPosts = async () => {
  const { data } = await useFetch('/api/posts', {
    method: 'POST',
    body: JSON.stringify(form)
  })
  posts.value = data || []
}

// if you want fetch when component mounts:
onMounted(getPosts) 
</script>

The template is quite basic, but it should give you an idea on how it's using the data and how it all works.
Modify form to use whatever query params your backend expects.


Update: Although the above is the recommended way in Nuxt3, Options API is still available. This should do it:

export default {
  data: () => ({
    posts: []
  }),
  methods: {
    async getPosts() {
      const { data } = await $fetch('/api/posts', {
        method: 'POST',
        body: JSON.stringify(this.form)
      })
      this.posts = data
    }
  }
}
like image 130
tao Avatar answered Oct 13 '25 23:10

tao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!