asyncData and fetch is not setting data

Viewed 2162

I am using nuxt v2.14.1 with typescript and nuxt-property-decorator package. I am facing lots of issues.

  1. I am not able 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
    

Vue dev tools show fruits as an empty array too.

Can anyone help me understand what's happening and how to solve it?

Here is the 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 above code works if I just rename fetch to mounted.

Also, when using asyncData, the code seems to work, and I see my car list, and then, when page loading completes, page autmatically becomes empty even though I can see cars listed in Vue dev tools.

Update: Not using nuxt context in fetch parameter seems to work. No idea why though.

1 Answers

Did you tried by just 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>[])
      }
    }
  },

By just returning it it should merge your return object with your data object.

They wrote it also in the docs: https://nuxtjs.org/api/

The result from asyncData will be merged with data.

Note here: Since asyncData() happens on the server side it doesnt have access to the vue instance with this

Warning: You don't have access to the component instance through this inside asyncData because it is called before initiating the component.

Related