Home > Back-end >  Async fetch results not transferred to data function
Async fetch results not transferred to data function

Time:07-28

I have the code below in the file _slug.vue

{{ feed }} always returns an empty array. The console.log(this.feed) in the async fetch functions logs the correct data( an array of three objects) returned from the api call(a custom strapi controller). But again, feed is empty in the page itself.

{{ category }} is works as intended, both in the page and the console.log inside the async fetch function.

I have tried change the api call to one that does not require a param and that works in another page and I still get an empty array.

What am I missing?

<template>
  <div>
    <h1>Feed - {{ category }}</h1>
    <p>{{ feed }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      feed: [],
      category: this.$route.params.slug,
    }
  },
  async fetch({ params }) {
    const category = params.slug
    console.log('slug: '   category)
    this.feed = await fetch(
      `http://localhost:1337/api/getCategory/${params.slug}`
    ).then((res) => res.json())
    console.log(this.feed)
  },
}
</script>

CodePudding user response:

I believe that your category property works as expected because you're setting it directly in the data function. You're not actually setting the category in the fetch function. I think that your problem is with the fetch function not being placed in the "methods" property. Try refactoring the code as follows: (note the fetch function placed in the methods object)

<template>
  <div>
    <h1>Feed - {{ category }}</h1>
    <p>{{ feed }}</p>
  </div>
</template>

<script>
export default {
  methods: {
    async fetch({ params }) {
      const category = params.slug;
      console.log("slug: "   category);
      this.feed = await fetch(`http://localhost:1337/api/getCategory/${params.slug}`).then((res) => res.json());
      console.log(this.feed);
    },
  },
  data() {
    return {
      feed: [],
      category: this.$route.params.slug,
    };
  },
};
</script>

CodePudding user response:

The comment from Kissu resolved my issue, not passing { params } to fetch() and using this.$route.params.slug instead.

CodePudding user response:

You should use fetch() without anything inside of () otherwise, you'll be using the old fetch as explained here: stackoverflow.com/a/68820416/8816585

Access the params through regular this.$route.params.slug.

  • Related