1

I wonder if there is a way to access object properties as keys returned by asyncData()?

data() {
    return {
       bookmark_btn: {
        status: null,
        loading: false
      }
   }
}

I tried access data object properties like below but didn't work.

async asyncData(){
    let activity = await axios.get('data.json')
    return { bookmark_btn.status: activity.status}
}

3 Answers 3

1

As mentioned before, because asyncData is a server rendered method you can't directly access your components data.

Previous solution works but I don't think it's how things are intended to work with Nuxt and it's complicated (using a 3rd party lib Vuex and messing around context object).

According to the API, asyncData will be merged into your data after loading the client side, which means you will have access to the returning value object of your page.

This mean you can use it directly to change the state of your page when the server side finishes loading so you either use the reactivity of vue and use it directly or you use the value within the mounted property of your page which is the solution for your use case.

Sign up to request clarification or add additional context in comments.

Comments

1

Use new fetch method instead of asyncData present in Nuxt >= 2.12 . this fetch method can have data properties.

async fetch() {
    let activity = await axios.get('data.json')

    this.$set(this.bookmark_btn, 'status', activity.status)
}

Check out more in official docs https://nuxtjs.org/api/pages-fetch/

Or to use old asyncData, remove data() from component as whatever asyncData will return, will append in data(). So you can try out this

  async asyncData() {
    let activity = await axios.get("data.json")
    return {
      bookmark_btn:{
        status: activity.status,
        loading: false
      }
    }
  }

2 Comments

your answer is partially correct in this case. as my architecture and use case does not support fetch method.
Actually its an API, for the sake of example i used data.json
1

if you put data in store can you easily git this data to asyncData function

export default {
  state: () => ({
    posts: [],
    selectedPost: {},
    page:3
  }),
  mutations: {
    updatePosts(state, posts){
      state.posts = posts;
    },
    updateSelectedPost(state, post){
      state.selectedPost = post;
    }
  }
}

that was store file

 asyncData({$axios , store }  ){
         return $axios.$get(`http://localhost:3001/data?_page=${store.state.page}&_limit=20`)
         .then( res =>{
           
                 store.commit("updatePosts", res);
          })
      },

that was index.vue file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.