The asyncData and fetch functions are failing to populate the data

I am currently working with nuxt v2.14.1 along with typescript and the nuxt-property-decorator package. I've been encountering a variety of issues.

  1. One of the problems I'm facing is the inability to set data from fetch() or asyncData.

    console.log(this.fruits) // => undefined
    console.log(response.data);//  => [{},..}
    this.fruits = response.data; // => this does not set fruits
    

Even Vue dev tools display fruits as an empty array.

Could someone shed light on what might be happening and provide guidance on how to resolve this issue?

Below is a snippet of code using fetch:

@Component({
  layout: 'AppLayout',
  async fetch({ query, store }: Context) {
    const self = this;
    const model = new Car();
    model.setFilters(query);
    const response = await model.$api.$get('/new/cars').catch(() => {
      store.$showError('Unable to fetch cars');
    });
    if (response) {
      // @ts-ignore
      self.cars = Car.collect(response.data as Partial<Car>[]);
    }
  },
})
export default class index extends Vue {
  cars: Car[] = [];
}

The provided code works when I rename fetch to mounted.

Furthermore, using asyncData seems to work initially as I can see my list of cars, but upon completion of page loading, the page automatically clears even though the cars are visible in Vue dev tools.

Update: I've noticed that not using nuxt context in fetch parameter seems to work. The reason behind this behavior is unknown to me.

Answer №1

Have you attempted simply returning an object?

  async fetch({ query, store }: Context) {
    const model = new Car();
    model.setFilters(query);
    const response = await model.$api.$get('/new/cars').catch(() => {
      store.$showError('Unable to fetch cars');
    });
    if (response) {
      return {
         cars: Car.collect(response.data as Partial<Car>[])
      }
    }
  },

When you simply return it, your return object should merge with your data object.

It is also mentioned in the documentation: https://nuxtjs.org/api/

The result from asyncData will be merged with data.

Keep in mind: As asyncData() runs on the server side, it does not have access to the vue instance using this

Warning: You cannot access the component instance with this inside asyncData because it is executed before the component is initialized.

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

Register with your Facebook account - Angular 4 Typescript

After extensive searching, I have yet to find a clear answer to my question... This is my first time delving into the world of Social Networks. I am curious to know if there are options for Facebook and Twitter sign-ins using Typescript. It seems that Go ...

Exploring Nested JSON Iteration in Angular4

I am struggling to iterate through a nested JSON and extract the desired output. Can someone assist me in retrieving the bpmn:startEvent id value from the JSON provided below? { "bpmn:definitions":{ "@attributes":{ "xmlns:xsi":"h ...

How can we leverage RxJS combineLatest for observable filtering?

I'm exploring the possibility of utilizing combineLatest in an Angular service to eliminate the need for the activeFiler$ switch block (The service should achieve the same functionality). Currently, this is the structure of the component design (stack ...

Encountering an error when trying to add Vue Router to a pre-existing Vue.js project

Encountered npm error code ERESOLVE which led to the inability to resolve dependency tree. The error occurred while trying to resolve the dependencies for "[email protected]". It was found that "[email protected]" was present in the vue node_modu ...

Setting up global Axios configuration with authentication in NuxtJS using VueJS

In my quest to configure Axios globally with authentication in NuxtJS - VueJS (primarily NUXTJS), I am facing a challenge. What I aim for is pretty straightforward: If a user is logged in and has a token in $store, I want Axios to use this token. If the u ...

Encountering Issue in Vue 3: Difficulty retrieving parameter values upon route change

Currently, I have coded a function called chooseProject(e): chooseProject(e) { let token = this.extractFirstText( e.title ); let userId = this.projects.user_id; this.$router.push('/dashboard/'+token ); localStorage.setItem( & ...

Get personal preferences from the server

I have an application built with Vue.js that requires user authentication. To achieve this, I utilize Vue Router along with protected routes. Upon successful login, the user receives an auth token from the server which is then stored in local storage. Bel ...

Integrating Vue.js code into Laravel's Blade templates for enhanced functionality

I'm having trouble accessing data from a Vue component function in a Laravel blade template that includes the component. When I use this code, the page just loads as a blank page. However, if I remove the @ symbol from the blade span, the autocomplete ...

Leveraging the useState hook with an array when retrieving data from the Redux store

When I go to the store, I always make sure to bring my family along with me. Here's how I access my family object from the top: const family:Family = useSelector((state:any) => state.family.family); This object represents my beloved family: addres ...

Implementing a PayPal Payment Button in Vuejs3 using the Composition API setup function

Attempting to integrate PayPal buttons into my Vuejs3 project using the Composition API (setup), I encountered errors. When attempting integration without using setup, everything works perfectly fine. Below is the working script: <script> ...

Updating the value of the chosen drop down option upon selection

I currently have a Material UI dropdown menu implemented in my project. My goal is to use the selected option from the drop down menu for future search functionality. How can I utilize onChange() to store the selected option effectively? At the moment, I ...

Issue with Vue.js: @input directive not functioning properly in conjunction with v-for directive

I've been working on developing my own custom <input> Vue component. I've implemented a feature that prevents users from inputting the wrong type of data by using regex.test() for each input field. Below is the code snippet for my Vue comp ...

A guide on verifying the presence of a v-data-table element using Cypress

The vuetify v-data-table component includes a feature called "show-select" which adds a checkbox to each list item. I am facing an issue where I need to check elements in the table for a Cypress test, but so far, it has not been successful. I assigned an i ...

The functionality of TypeScript's instanceof operator may fail when the method argument is not a simple object

There seems to be an issue with a method that is being called from two different places but returns false for both argument types. Despite checking for the correct types, the problem persists and I am unsure why. Although I have read a similar question on ...

The route parameters in Vue SSR are being retrieved from a separate request

I am currently using Akryum/vue-cli-plugin-ssr along with vue-cli, but I have encountered an unusual issue in my Vue SSR application. It seems that the route params are getting mixed up with requests made either before or in parallel to the current one. F ...

What is the reason for the lack of variable assignment within the forEach method in Angular?

I am struggling with assigning a value to the variable "this.qdDias" and returning it. After using subscribe, I am unable to retrieve the value at the end of the method. Despite seeing the value in the console.log(this.qdDias), it becomes undefined when re ...

Incorporating Close, Minimize, and Maximize functionalities into a React-powered Electron Application

Struggling with implementing minimize, maximize, and close functionality for a custom title bar in an electron app using React Typescript for the UI. The issue lies within the React component WindowControlButton.tsx, as it should trigger actions to manipu ...

Generic Typescript Placeholder Design

Imagine you have the following data: const dataA = { name: "John", age: 25, attributes: {specificA: "hello", specificA2: 14, nonspecific:"Well"}, } const dataB = { name: "Lisa", age: 38, attributes: {spe ...

Conditional application of Angular animations is possible

After implementing the fadein effect from Angular-Animations in my ASP.NET based Angular project, I encountered an issue where only the first row is faded-in while the other rows are not displayed when using *ngIf. Here is a snippet of the code: <ng-te ...

Upload a file to a Google Cloud Storage bucket using axios

Seeking assistance with uploading a file to a google cloud bucket using vuejs and axios. Successfully implemented through an html form: <form action="https://storage.googleapis.com/some-bucket" method="post" enctype="mul ...