Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refresh the data obtained by Async Data() in NuxtJs?

In NuxtJs app i got data() on server side by AsyncData() method.

For example, I need to delete one entry and refresh the page without restarting the browser.

In pure Vue, I would write an ajax method to update the data from the server after removal. Usually this method is the same as for the initial load and it is located in "mounted". But NuxtJs can't I access a method async Data() again. Or can I?

   async asyncData({$axios, params}) {
        const {data} = await $axios.$get(`/topics/${params.id}`)

        return {
            topic: data
        }
    },

  -------------------------

   async deletePost(id) {
            await  this.$axios.$delete(`/topics/${this.topic.id}/posts/${id}`)
                // bad idea - hard reset
                   window.location.reload(true)
                //how refresh by asyncData()?
    },
like image 852
Ilya Vo Avatar asked Nov 27 '22 16:11

Ilya Vo


2 Answers

This is easily done using the $nuxt helper, in any component:

await this.$nuxt.refresh()

See https://nuxtjs.org/docs/internals-glossary/$nuxt/#refreshing-page-data

like image 136
Thijs Avatar answered Dec 04 '22 07:12

Thijs


You can not access the asyncData method because it is called by nuxt on the server side before render. However, you can of course manipulate your data object that mirrors your asyncData. So i guess you have a data component like this:

data() {
  return {
    topic: [],
  }
}

which is merged with what asyncData returns and is what is shown in the client. So without having to reload your page you can manipulate 'topics' and it will be reflected in the client. Something like this:

async deletePost(id) {
  await this.$axios.$delete(`/topics/${this.topic.id}/posts/${id}`)
  this.topic... //change it to reflect what was deleted.
},

Or You can then make another api call after your delete call in the same method.

await this.$axios.$delete(`/topics/${this.topic.id}/posts/${id}`)
  let {data} = await $axios.$get(`/topics/${this.topic.id}`)
  return this.topic = data
},

Either way, you update the 'topic' array after the delete call and that is what is shown in your client.

like image 31
Andrew1325 Avatar answered Dec 04 '22 06:12

Andrew1325