The categories in Vue are not being displayed after they have been fetched

Looking for assistance with Vue rendering. Currently, I am developing a Vue-Wordpress application and facing an issue with retrieving a list of categories for each post. The categories for every post are fetched from the WP API as their respective IDs. I am passing the categories' IDs as props to a child element (prop "cats") and attempting to render them after fetching their names. However, I am not seeing anything on the front-end (although in the Vue dashboard I can view a list of category names, unfortunately, I cannot share an image of it).

 <template>
  <div class="bg-white border rounded border-black border-collapse">
    <h2 class="font-bold text-xl p-2 hover:text-gray-600 cursor-pointer">{{ title }}</h2>
    <div
      class="w-full h-48 bg-cover bg-center"
      :style="{ 'background-image': 'url(' + image + ')' }"
    ></div>
    <div class="px-4 py-2">
      <p class="text-gray-700 h-40 text-base" v-html="content"></p>
      <div>
        <span
          v-for="(val, index) in categories"
          :key="index"
          class="inline-block bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700 mr-2"
        >{{val}}</span>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: ["title", "content", "image", "cats"],
  data() {
    return {
      categories: {}
    };
  },
  created() {
    this.getAll();
  },
  methods: {
    getAll: function() {
      this.$props.cats.forEach(r => this.getCatName(r));
    },
    getCatName: function(id) {
      fetch(`http://rest-api.local/wp-json/wp/v2/categories/${id}`)
        .then(r => r.json())
        .then(res => (this.categories[id] = res.name));
    }
  }
};
</script>

Answer №1

If you are encountering a reactivity issue, it is recommended to utilize the this.$set method:

 .then(res => (this.$set(this.categories,id,res.name)));

Also, ensure that the id property is properly initialized:

 data() {
    return {
      categories: {
       id:null
       }
    };
  },

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

Is Q.js capable of functioning independently from node.js and require()?

Currently experimenting with the latest version of q.js to integrate promises into my ajax calls without utilizing node.js at all. I retrieved the most recent version from https://github.com/kriskowal/q and only included q.js in my project. While testing, ...

Validation of Regular Expressions in Javascript

I am trying to implement control validation using Javascript. The validation criteria states that the number should consist of a maximum of 12 digits, with the first 7 being '9900000' followed by either a '0' or a '1', and en ...

Learn how to incorporate slide transitions into the dropdown menu of a navbar in Bootstrap 4, complete with Vue.js transition effects

I'm attempting to incorporate a slide up and down transition into the bootstrap 4 dropdown menus using vue transitions. Unfortunately, the transition isn't functioning as expected. Even after utilizing the transition element, the animation stil ...

What is the process for using jQuery to systematically alter the src attribute of all avatar images on Twitter.com?

Summary: I am learning JavaScript and jQuery, and wanted to write a script to replace "_normal.png" with ".png" for all "img.avatar" images on Twitter.com. I encountered an error which I will explain below. Background: Practice makes perfect, so I like to ...

Enhancing Numerical Visuals: Tips for Optimizing Visualization of Proximate Numbers using

In my chart, I noticed that the values are very close together such as: Value A -> 3.7747199435 Value B -> 3.775531821 Value C -> 3.7754975674 Value D -> 3.8358619466 Value E -> 3.8856710034 and as a result, the visualization shows minima ...

Custom mute bot using Discord.js with the ability to specify duration and provide a reason

I'm creating a discord.js mute bot and encountering some issues with its functionality. Is there a way to program it so that when someone types the command !mute User, it automatically sets the time to 30min and the reason as No reason Specified. How ...

Enable the feature for users to upload images to a specific folder within the Chrome extension without the need for

I need to implement a feature in my Chrome extension that allows users to upload images directly to a specific folder named "upload" without needing a submit button. <form action="/upload"> <input type="file" name="myimages" accept="image/*"> ...

How can the value attribute be obtained from the click class?

$(document).on('click','.edit', function(){ var appid = $(this).getAttribute('value'); I am trying to figure out how to save the value of the "value" attribute for an image with the edit class. Can anyone help me with thi ...

Ways to utilize the map() function with data retrieved from an axios response?

Utilizing axios for data retrieval from the server and then storing it in the state. However, when attempting state.map( post => {console.log(post)} ), no output is displayed. The technologies being used are Express, Mongoose, NextJS, and Axios. My ap ...

What is the best way to transform this code into a JavaScript string that can be evaluated at a later time?

I need a way to save this snippet of JavaScript code, make some modifications to it, and then evaluate it at a later time. Unfortunately, the online converter I tried using didn't produce the desired outcome. Original Code $Lightning.use("c: ...

Angular Flot Chart Resizing: A Guide to Dynamic Chart S

I have successfully integrated a Flot chart into my HTML using an Angular directive. Here is how it looks: <flot id="placeholder" dataset="dataset" options="options" height="300px" width="100%" style="width:100%;" ng-disabled="graphLoading" ng-class="{ ...

Calculating the sum of values in a JSON array using a specific parameter in Typescript

A flat JSON array contains repetitive identifier, categoryId, and category: data: [ { "identifier": "data", "categoryId": "1", "category": "Baked goods", "product": "Aunt Hattie's", "price": "375" } ...

Explore the category options in the reference document using Node.js

Category Schema const CategorySchema = mongoose.Schema( { catName: { type: String, required: true } }, { timestamps: true } ); Product Schema const ProductSchema = new mongoose.Schema( { brand: { type: String, required: true }, title: ...

How to toggle between displaying divs using JavaScript and Jquery

How can I use JavaScript to show or hide specific divs on page load and upon clicking different links? I want to display the "houseImages" div by default, while hiding the "landImages", "renovationImages", "UpcomingImages", and "voteForNext" divs. Then, w ...

Is it possible to invoke a helper function by passing a string as its name in JavaScript?

I'm encountering a certain issue. Here is what I am attempting: Is it possible to accomplish this: var action = 'toUpperCase()'; 'abcd'.action; //output ===> ABCD The user can input either uppercase or lowercase function ...

Prevent parent element from triggering double click when double clicking on children element with CSS or jQuery

Check out my project demo here Whenever I double click on a child element, it also triggers the parent element at the same time. I want to prevent this behavior so that only the child element is affected by the double click event. Can anyone provide assis ...

Tracker.autorun subscription triggers repeated firing of publish callback

Working on a ReactJS and Meteor project, I encountered an unexpected behavior that I would like to discuss here: Within the code, there is a block with Tracker.autorun containing a call to Meteor.subscribe. On the server side, there is a corresponding Met ...

Toggle the hamburger menu using JavaScript

How can I close my hamburger menu when clicking a link for one page navigation? The menu is functioning properly, but I need a way to close it. Unfortunately, I have limited knowledge of JS. I only have the HTML and CSS for this: HTML in index.html file ...

The server's delayed response caused the jQuery ajax request to be aborted

Encountering delayed AJAX response from the PHP server upon aborting the AJAX request. Currently utilizing the CodeIgniter framework for the server script. Javascript Code: cblcurrentRequest = $.ajax({ url: baseurl + 'Login/getChannelBra ...

Assign the value of "td" to the variable "val"

I am trying to set the value of my td element from my JavaScript JSON, but for some reason it doesn't seem to be working when I inspect the element. The HTML is functioning fine, it's just the value that isn't updating. I've tried chang ...