Fetching information from a data object using asyncData in Nuxt

Is there a method to retrieve object properties as keys from the asyncData() function?

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

I attempted to access data object properties in the following way, but it was unsuccessful.

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

Answer №1

Just to reiterate, because the asyncData method is server-rendered, accessing your component's data directly is not possible.

The previous workaround may be effective, but it seems to go against the intended usage of Nuxt and involves complexities like using a third-party library like Vuex and manipulating the context object.

As per the information provided in the API documentation, the data fetched by the asyncData method will be integrated into your component's data after the client-side load, granting you access to the returned value object of your page.

This implies that you can utilize this data directly to update the state of your page once the server-side rendering is complete. You have the option to leverage Vue's reactivity for direct usage or incorporate the value within the mounted property of your page, offering a tailored solution for your specific use case.

Answer №2

Implement the new fetch method instead of using asyncData in Nuxt version 2.12 or higher. The fetch method allows for data properties to be defined.

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

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

For more information, refer to the official documentation at https://nuxtjs.org/api/pages-fetch/

If you prefer to stick with the old asyncData method, simply remove the data() function from the component. asyncData will automatically append its return value to data(). You can follow this example:

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

Answer №3

Is it possible to access data stored in the store within the asyncData function?

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

This is the content of the store file.

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

This is the content of the index.vue file.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error in GraphQL query: specified argument is mandatory, yet not supplied

I recently started learning about graphql and encountered an issue with my query. Here is the code I am using: { product { id } } "message": "Field "product" argument "id" of type "String!" is requir ...

Tips for rearranging objects within a jsPDF document to prevent vertical overlap when a table grows in size

I am new to React and Javascript. I have been struggling to find a solution to my issue while trying to create a .pdf document for a customer invoice using "jsPdf" along with its plugin "jspdf-autoTable". So far, everything is being generated correctly by ...

Expand and enhance your content with the Vue Sidebar Menu plugin

Recently, I integrated a side-bar-menu utilizing . My goal is to have a sidebar menu that pushes its content when it expands. Any suggestions on which props or styles I should incorporate to achieve this effect? Below is my Vue code: <template> ...

Nested Tab Generation on the Fly

My goal is to create dynamically nested tabs based on my data set. While I have successfully achieved the parent tabs, I am encountering an issue with the child tabs. Code $(document).ready(function() { var data1 = [["FINANCE"],["SALE"],["SALE3"]]; var da ...

Issue encountered while retrieving information using Axios in a Vue.js application

Currently, I am in the process of developing a full stack application using Vue.js and Fastify.js (a Node framework). The Vue app is supposed to retrieve data from the API I created and display it in the browser console. However, I am encountering an issue ...

What is the best way to fetch all the orders from my product schema using response.send?

This is my custom Product schema const productSchema = new mongoose.Schema({ title: { type: String, required: [true, "Title is required"] }, details: { type: String, required: [true, "Details are r ...

After swapping out "div" with "input" and then replacing "input" with

My goal is to create a function where a user can edit text within a div. The idea is to replace the current text with an editable input field, and then convert it back into a div after the user hits enter. I've encountered an issue while trying to im ...

Warning on React component listing due to key issue originating from the parent component

Alert: It is essential that each child in a list has a distinct "key" prop. Please review the render method of ForwardRef(ListItem). A child from RecipientsList was passed. I have located this issue using the react-components debugger tool on Chrome. I ad ...

Managing data in a database on Discord using JavaScript to automatically delete information once it has expired

Recently, I implemented a premium membership feature for my discord bot. However, I encountered an issue where the membership time starts counting down before the intended start time. To resolve this, I am looking to automatically delete the data from the ...

Can someone please help me figure out how to detect active users within my Next.js application while utilizing Supabase authentication?

I'm looking for a way to recognize users on my app in order to display green badges as visual cues. After logging into my app using Google OAuth, the session remains active even though I logged out days ago. I am unsure of the most effective algorith ...

How can we utilize the parameter extracted from an input element in vue.js?

I have the knowledge of extracting value from an input element. <div id="app-6"> <p>{{ url }}</p> <input v-model="url"> </div> <script> new Vue({ el: '#app-6', data: { url: '' } } ...

Vue Component Unit Testing: Resolving "Unexpected Identifier" Error in Jest Setup

Having just started using Jest, I wanted to run a simple unit test to make sure everything was set up correctly. However, I encountered numerous errors during compilation while troubleshooting the issues. When running the test suite, Jest successfully loc ...

Exploring the power of Vue by processing components on a local

I have come across this code: <my-messages> <message>Hello</message> <message>World</message> </my-messages> Currently, my <my-messages> component is rendered as: <div class="Messages"> <!-- ...

Jquery animation is dragging its feet on Explorer, while other browsers are zipping along

Hey everyone, I am facing an issue with a simple jquery plugin I created for an animated menu. You can check out the entire site here: Main website My Library the "bootstrap" file The problem is that the red rectangle animates smoothly in Firefox, Op ...

Is JavaScript Promise Chaining Allowed?

I have a question regarding my code, despite it currently functioning correctly. Specifically, I'm wondering if the sequence of promises in my database is valid. Promise 1 must be fulfilled before moving on to Promise 2 because I rely on the data and ...

The splash screen fails to show up when I launch my Next.js progressive web app on iOS devices

Whenever I try to launch my app, the splash screen doesn't show up properly. Instead, I only see a white screen. I attempted to fix this issue by modifying the Next Metadata object multiple times and rebuilding the PWA app with no success. appleWebApp ...

The functionality of Bootstrap toggle ceases to operate properly following an AJAX content update

I am currently using AJAX load to fetch some content on my webpage. I am working with Bootstrap 3 and Bootstrap toggle. When the content is loaded, the Bootstrap 3 content functions properly (the panel-primary panel is clearly visible). However, the Bootst ...

The Shopify Pixel Extension has encountered an issue - error code 1

Looking to develop a web pixel extension for my Shopify app, I followed the official guide: While building the app, encountered this error: extensions | my-app-pixel (C:\projects\shopify\my-app-pixel\node_modules\.bin\shopify ...

Converting the given data into an object in JavaScript: a step-by-step guide

"[{'id': 3, 'Name': 'ABC', 'price': [955, 1032, 998, 941, 915, 952, 899]}, {'id': 4, 'Name': 'XYZ', 'id': [1016, 1015, 1014, 915, 1023, 1012, 998, 907, 952, 945, 1013, 105 ...

You are trying to access the "title" property or method in the render function, but it is not defined in the instance. To ensure reactivity, make sure that

I am currently working with parent and child components, trying to pass props between them. The parent component is named "links" and the child component is called "link-encoded." In the HTML template, I have included the child component like this: <li ...