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

The next function is not defined error in the controller function

Everything was running smoothly until I suddenly encountered this error message: ReferenceError: next is not defined. I'm puzzled because I didn't make any changes to this function. const Users = require('../data/users.model') exports ...

Identify the location of the mouse and activate a specific function based

Tracking the x-coordinate of the mouse is crucial in this scenario. When the mouse approaches a specific threshold (250px) towards the left edge of the window, it should trigger the function "openNav." The function should close when the mouse moves away fr ...

Arrange pictures into an array and showcase them

I'm encountering some difficulties with organizing my images in an array and displaying them in a canvas element. Javascript code snippet canvas = document.getElementById('slideshow'); canvasContent = canvas.getContext('2d'); va ...

Using onClick function to pass the value of an input textbox in PHP

I have an input text field and I am looking to pass the values entered inside the element through a JavaScript onClick event. <form> <fieldset> <label>Common Site ID: </label><span><?php echo $commonsiteid ?>< ...

Configuring Node.js HTTPS to function alongside HAPROXY

My goal is to establish communication between my nodejs app and HAPROXY using HTTPS. The plan is for nodejs to send a message to haproxy via https, and haproxy will then route the message accordingly. Initially, I had success with the request.js library, ...

AngularJS: splitting the parent <div> into multiple sections every nth element

I have an array of strings in Javascript and I am attempting to use AngularJS to create nested <div> elements. var arr = ["abc", "def", "ghi", "jkl", "mno", "pqr", "stu"]; My goal is to group every 3 elements together like so. <div class="pare ...

Having issues updating cookies with jQuery in ASP.NET framework

On my asp.net web page, I have implemented a search filter functionality using cookies. The filter consists of a checkbox list populated with various categories such as sports, music, and food. Using a jQuery onchange event, I capture the index and categor ...

Leverage Hubspot and Google Analytics to transfer session source and medium data

Is there a way to track session source and medium information in HubSpot to identify where a specific visit originated from before a form is filled out or another conversion event occurs? Ideally, this process would involve transferring the session and me ...

The retrieval of data using PHP, MYSQL, and AJAX is unsuccessful

A dropdown menu contains the names of months, represented by numbers from 1 to 12: When a month is selected, I want to retrieve data from a database to display relevant tournaments for that specific month. The SQL code has been tested and confirmed to be ...

Displaying Product Attribute and Category Names in Woocommerce Title

After reading the answer provided in this thread (Woocommerce: How to show Product Attribute name on title when in a category page and "filtering" products via '?pa_attribute=' on address bar), I am interested in displaying both the categ ...

Incorporate JavaScript code into an Angular UI-Router view

I can't seem to find an answer to this question anywhere, so I'm hoping someone here can help me out. In my AngularJS app, I am using ui-router to load multiple views into the same <ui-view> element. I am trying to implement Jquery UI&apos ...

Is it possible to retrieve a callback function from a select event in the Bootstrap dual listbox?

I'm fairly new to front-end development and have been using the Bootstrap DualListbox for a project. I'm looking for a way to save items moved from one list to another to a database before they are officially transferred. Is there a callback func ...

During operational hours, an Ajax request may cause interruptions to the website's functionality

Having an issue with a large ajax request: I am querying a PHP file that makes some cURL requests, taking 15-20 seconds to complete and then returning JSON on my webpage. It's a standard ajax request, but I found a strange bug. While the ajax query i ...

What is the best method for showing jQuery/Javascript functions in the HTML <pre> element as a string

I am curious about converting jQuery or JavaScript functions to a string and displaying them in an element like <pre> HTML : <pre></pre> jQuery : function test() { alert('test'); } $('pre').html(test()); // &l ...

Is there a way to rotate the custom marker icon in vue2-google-map?

After reading the documentation, I discovered that using path is the only way to rotate the marker. In an attempt to customize my marker, I created my own PNG image. However, I have been unsuccessful in overriding the CSS of the marker. I even tried to ov ...

Utilizing a segment of one interface within another interface is the most effective method

In my current project using nextjs and typescript, I have defined two interfaces as shown below: export interface IAccordion { accordionItems: { id: string | number; title: string | React.ReactElement; content: string | React. ...

Attempting to retrieve access token for Paylocity Web API in Node.js, encountering the issue of receiving an "invalid_client" error message

I've been attempting to retrieve the access token for the paylocity API. I can successfully obtain it through postman using the client id and client secret, but when I try to do so with Node.js, I receive the message {"error":"invalid_client"}. Below ...

"Enhancing User Experience with AngularJS by Dynamically Modifying and Refresh

I'm currently attempting to dynamically add HTML elements using JavaScript with a directive: document.getElementsByClassName("day-grid")[0].innerHTML = "<div ng-uc-day-event></div>"; or var ele = document.createElement("div"); ele.setAttr ...

Issue with Karma and angular-mocks: The error message "TypeError: 'undefined' is not an object (evaluating 'angular.mock = {}')" is being shown

I am facing an issue while writing unit tests using Karma + Jasmine. The problem arises with angular-mocks when I run grunt test, resulting in the following error message: PhantomJS 1.9.8 (Mac OS X) ERROR TypeError: 'undefined' is not an ob ...

Is it possible to share data from one controller in a JS file to another JS file? (using AngularJS)

I need to create a table in JavaScript. In one of my JS files, I have a controller with JSON data containing properties like width, height, color, etc. In another JS file, I am building the actual table structure. Here is an example of my AngularJS file: ...