In Vue.js, when an if-else statement is nested within a loop, it will display the

I'm trying to create a loop that displays blog posts. Within this loop, I have another loop to retrieve the likes for each blog post. My goal is to show an "unlike" button if the authenticated user has liked the blog post, and a "like" button if they haven't. However, the issue is that the main loop is displaying two buttons instead of one when multiple users have liked the same post.

<div class="post" v-show="blogs.length" v-for="blog in blogs" :key="blog.id">
  <span v-for="like in blog.likes" :key="like.id"> 
    <span v-if="blog.id === like.blog_id && like.user_id === authUserId">
      <a href="#" class="link-black text-sm">
        <i class="fas fa-thumbs-down mr-1"></i> UnLike ({{blog.likes.length}}) 
      </a>
    </span>
    <span v-else>
      <a href="#" class="link-black text-sm">
        <i class="fas fa-thumbs-up mr-1"></i> Like ({{blog.likes.length}} )
      </a>
    </span>
  </span>
</div>

Can anyone help me figure out what I'm doing wrong?

The conditions don't seem to be working as expected.

Answer №1

To optimize performance, consider checking if the user liked each blog only once instead of using an inner loop:

<div class="post" v-show="blogs.length" v-for="blog in blogs" :key="blog.id">
  <span v-if="blog.likes.find(like => like.blog_id === blog.id && like.user_id === authUserId)">
    <a href="#" class="link-black text-sm">
      <i class="fas fa-thumbs-down mr-1"></i> UnLike ({{blog.likes.length}}) 
    </a>
  </span>
  <span v-else>
    <a href="#" class="link-black text-sm">
      <i class="fas fa-thumbs-up mr-1"></i> Like ({{blog.likes.length}})
    </a>
  </span>
</div>

Check out this demo

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

Unable to retrieve React state within the callback function

As I work with the following components: const ParentComponent: React.FC = () => { // Setting newType to some value within the code const [newType, setNewType] = useState<any>(undefined); // Enabling addEdge to true in another part o ...

Facing an issue where the Strapi image is not displaying on the _slug.vue page in my Nuxt

I'm having trouble displaying my Strapi images on the _slug.vue page. I've successfully displayed the title and content from Strapi, but when I include the image code, the page fails to render properly. <div class="article__container& ...

Utilize Vue and JSON to dynamically fill select options based on another select input

Seeking assistance in developing a dynamic search form with select options for Districts, Regions and locations. The Regions selection should be populated based on the selected District, and the Locations based on the chosen Region. The data is structured ...

Error: Improper hook call detected with no hooks being used (material-ui v5)

I've created the following basic application: import Grid from '@material-ui/core/Grid'; function App() { return ( <div className="App"> <Grid container spacing={2}> <Grid item xs={8}> ...

What advantages come from selectively importing a single function from a Node.js package on the backend, rather than importing the entire package?

Consider a scenario where I only require the ObjectId function from the mongoose package in my file. Are there any advantages (in terms of CPU usage, memory consumption, speed, etc.) to importing just that specific function instead of the entire mongoose ...

What is the most reliable method for converting a 32-bit unsigned integer to a big endian byte array?

Looking for a simple and reliable method to convert an unsigned integer into a four-byte-array in big endian format, with padding if necessary? Take a look at this example: Input value: 714 Output: Resulting byte array [ 0xca, 0x02, 0x00, 0x00 ]; By the ...

Ways to adjust the vAxis and hAxis labels to display as whole numbers

Below is the code provided: var rawdata='".$performances."'; var mydata=jQuery.parseJSON(rawdata); if(mydata){ var realData=[]; realData=[ ['Activities', &a ...

Create a JavaScript file that will generate a map based on data from an SQL

I am currently working on developing a Leaflet map with numerous markers. To streamline the process of updating the map, I have stored all the markers in a MySQL database. A PHP script is utilized to retrieve the data from the database, format it in a way ...

Harnessing the Power of NextJS Image Component and @svgr/webpack for Seamless Integration

I have recently set up a Next.js site utilizing the @svgr/webpack library. In order to start using an SVG image with the new next/image component, I configured my next.config.js file accordingly. My next.config.js setup looks like this: module.exports = { ...

Create a submit button using Vue.js for text input

Can anyone help with a beginner question? I have a form that includes a text field. When I type something in and press enter, no result shows up. However, when I type something in and click the button, I get the desired result. Could someone guide me on ...

Dealing with error management in Transfer-Encoding chunked HTTP requests using express and axios

My current challenge involves fetching a large amount of data from a database in JavaScript using streaming to avoid loading all the data into memory at once. I am utilizing express as my server and a nodeJS client that retrieves the data using Axios. Whil ...

Ways to retrieve the value of 'this' within the state of a Vuex store module

Imagine a scenario where there is a "store" directory structured as follows: ... store ├── auth │   └── user.js └── index.js ... index.js import Vue from 'vue'; import Vuex from 'vuex'; import {user} from ' ...

Ensuring Data Integrity in Angular JS Forms

I've been working on submitting a blank form that triggers custom error messages on mandatory fields. The validation is working perfectly, but I'm running into an issue when the form is loaded for the first time and the user clicks directly on th ...

Technique for identifying a sequence within a longer numerical series

As I ponder this puzzle for what seems like an eternity, I humbly turn to you for a possible solution. A lengthy number resembling this one: 122111312121142113121 It is crucial to note that no numbers exceed four or fall below one. Now my quest is to une ...

Learn how to import from a .storybook.ts file in Vue with TypeScript and Storybook, including how to manage Webpack configurations

I'm currently utilizing Vue with TypeScript in Storybook. Unfortunately, there are no official TypeScript configurations available for using Vue with Storybook. How can I set up Webpack so that I am able to import from another .storybook.ts file with ...

jqGrid is failing to display basic JSON data properly

As a newcomer to Jquery and Json, I am struggling with binding a JSON object from a RESTful Webservice written in WCF to jqGrid. Despite saving the JSON object as a static file and attempting to bind it to the grid, I realized that the issue does not lie w ...

Sharing information between controllers while being initiated using $rootScope.$emit

I've created a common module that includes a controller, component, and template to initialize the app and set up the base layout. Within this module, there is also a stateful component that makes an HTTP GET request during initialization to fetch a b ...

Is it feasible to add on to an existing object in the database? (Using Node.js and Mongoose

After saving an object to the database using the following code: var newObject = new PObject({ value : 'before', id : 123456 }); newObject.save(function(err) { if (err) ...

Sequelizejs establishes a belongsToMany relation with a specified otherKey

I am currently developing an app centered around songs and artists, and here is the database schema I have designed: Each Song can have multiple Artists associated with it, and each Artist can be linked to several Songs as well. This establishes a many-to ...

Updating the title of a page on CoreUI's CBreadcrumbRouter dynamically

I'm currently developing a project with VueJS and the CoreUI admin template. Is there a way I can change the title of the current page as shown on the CBreadcrumbRouter? The GitHub documentation mentions that the script typically displays meta.label ...