Ways to update the DOM once a function has been executed in VUE 3 JS

I'm working on implementing a "like" or "add to favorite" feature in VUE 3. However, I'm facing an issue where the UI doesn't update when I like or unlike something. It only refreshes properly. I'm using backend functions for liking and disliking, which are functioning correctly. Can anyone help me with this?

Here is the code of the Parent component:

<Suspense>
        <template #default>
          <div class="is-flex is-1 is-flex-wrap-wrap" v-if="recipes">
            <RecipeCard
              class="card radius-small mx-2 my-3 p-3"
              v-for="(recipe, i) in recipes"
              :recipe="recipe"
              :key="i"
              :savedDishesId="savedRecipesIds"
              @openRecipe="openFunc(recipe)"
              @likeIndividual="isLiked(recipe)"
            >
            </RecipeCard>
          </div>
        </template>
      </Suspense>

import RecipeCard from '../components/recipe-cards/recipeCard.vue'

const recipeStore = useRecipeStore(),
  userStore = useUserStore(),
  loginStore = useLoginStore(),
  router = useRouter()
const recipes = ref([]),
  username = ref('User'),
  savedRecipesIds = ref([])

onMounted(async () => {
  fetchData()
  let userId = VueCookies.get('id')
  if (userId) {
    let user = await userStore.fetchAccDetails(VueCookies.get('id'))
    username.value = user.username
  }
  savedRecipesIds.value = await userStore.fetchSavedDishesId(userId)
  console.log(savedRecipesIds.value)
})

async function isLiked(userId) {
  console.log("parent");
  savedRecipesIds.value = await userStore.fetchSavedDishesId(userId)
}
async function fetchData() {
  recipes.value = await recipeStore.getRecipes()
}
console.log(loginStore.isAuth())

function openFunc(recipe) {
  router.push({ path: `/recipe/${recipe._id}` })
}
</script>

THE CHILD COMPONENT:

<template>
  <div class="recipe-card bg-color-white" style="cursor: pointer">
    <div class="card-head" @click="emits('openRecipe')">
      <figure class="">
        <img :src="props.recipe.img" alt="Recipe Image" class="image radius-default" />
      </figure>
    </div>
    <div class="card-desc" @click="emits('openRecipe')">
      <h3 class="is-size-3 color-tx-sec">{{ props.recipe.dish_name }}</h3>
      <p class="is-size-5">{{ resizeText(props.recipe.description) + '...' }}</p>
    </div>
    <div class="is-flex is-justify-content-space-between is-align-items-center is- mt-3">
      <p class="has-text-link" @click="emits('openRecipe')">View more</p>
      <Icon
        icon="ph:heart-bold"
        v-if="!isLiked"
        style="height: 2rem; width: 2rem"
        @click="toggleLike()"
      ></Icon>
      <Icon
        icon="mdi:heart"
        color="red"
        v-else
        style="height: 2rem; width: 2rem"
        @click="toggleLike()"
      ></Icon>
    </div>
  </div>
</template>

<script setup>
import { Icon } from '@iconify/vue'
import { computed, onMounted, ref, watch } from 'vue'
import { useUserStore } from '../../stores/userStore'

import VueCookies from 'vue-cookies'

const isLiked = ref(false)
onMounted(() => {
  updateLikeStats()
})

watch(
  () => props.savedRecipesIds,
  () => {
    updateLikeStats()
  }
)

const userStore = useUserStore(),
  userId = ref(VueCookies.get('id') || null)
const emits = defineEmits(['openRecipe', 'likeIndividual'])
const props = defineProps({
  recipe: {
    type: Object,
    required: true
  },
  savedRecipesIds: {
    type: Array,
    required: true,
    default: () => []
  })

// Function for resizing the description
function resizeText(text) {
  return text.slice(0, 120)
}

async function toggleLike() {
  await userStore.toggleLikeRecipe(props.recipe._id, { userId: userId.value })
  emits('likeIndividual', userId.value);
  updateLikeStats()
}

function updateLikeStats() {
  isLiked.value = props.savedRecipesIds.includes(props.recipe._id)
  console.log(isLiked.value)
}
</script>

Answer №1

It is my understanding that the fetchdata() function in onmounted retrieves data from the server. You can simply invoke this function whenever a like or dislike button is clicked.

Alternatively, you could make a single backend call to receive updated like and dislike information.

Answer №2

Apologies everyone, I have identified the issue in my code. It turns out the bug was located within the toggleLike() function.

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

The background image fails to display properly on the server in Next.js

Hello, I'm currently using NextJs and I have a challenge. I want to set a background image on the body element that is rendered server-side. Below you'll find my code snippets: First, here is my App.js: import BodyStyle from '@components/Bo ...

Organize the HTML output generated by a PHP array

There must be a simple solution to this, but for some reason, it's escaping me right now. I've created custom HTML/CSS/JS for a slider that fetches its content from an array structured like this: $slides = [ [ 'img' = ...

Encountering a duplicate key error in ExpressJS collection

Whenever I try to create a new event with categories that already exist in my database, such as creating an event with the category "javascript" and then attempting to create another event with categories "javascript, html, css", I encounter the error mess ...

Discovering the current time and start time of today in EST can be achieved by utilizing Moment.js

Need help with creating Start and End Time stamps using Moment.js in EST: Start Time should reflect the beginning of today End Time should show the current time. This is how I have implemented it using moment.js: var time = new Date(); var startTime=D ...

Exploring the effectiveness of React Hook Form using React Testing Library

My Component includes a form that, upon submission, utilizes Apollo's useLazyQuery to fetch data based on the form values. The form in the component is managed by React Hook Forms, with the handleSubmit controlled by RHF. <FormContainer onSubmit= ...

Scrape data from websites where the main URL remains constant but the information in the table varies

If you take a look at this link, you'll notice that when the next page is selected, the table on the website gets reloaded with new content without any change in the URL. Even after inspecting the developer tools > Network > XHR, it's difficult t ...

The Node.js application is unable to execute due to the error: "View "error" could not be found in the views directory."

Currently, I am following a tutorial that covers the integration of social login with Passport and Node. You can find the tutorial here: Tutorial Link In line with the tutorial, I have started working on a project while utilizing Windows 10 operating syst ...

Tips for utilizing jQuery Ajax data action

I've been trying to understand how to effectively utilize the data parameter in a $.Ajax call. However, I am facing confusion regarding the 'action' part within the data call. Is it meant to trigger an action in a controller? If so, how can ...

How to use jQuery to extract a particular text from an anchor tag

If I want to choose a specific anchor text and make changes to it, I can do so by targeting anchors with a certain href attribute. For example, on a page with multiple unordered lists, each containing different links: <ul> <li><a href="v ...

What is the best way to retrieve the current complete URL in a Next.js/Typescript component?

I'm working on a component and I need to retrieve the current full URL. Here's a simplified version of what I have: /** * Share dropdown component */ export const ShareDropdown: React.FC<{ className: string }> = ({ className, }) => { ...

Experience seamless slide transitions with the react-slick carousel using scroll events in React JS and JavaScript

Currently utilizing the carousel library found at: react-slick I am interested in enabling mouse scroll functionality to navigate through each slide. The idea is to scroll up to progress forward and scroll down to go backward. Came across a relevant exa ...

angular $stateProvider behaving unexpectedly with routing

Within my main file titled index.html, I have incorporated the following basic markup... <body ng-app="starter" ng-controller="AppCtrl"> <div ui-view></div> </body> In my separate file called app.js, I am utilizing $stateProvi ...

When the next button is clicked, the button content disappears

I am struggling with a problem involving two buttons that store tables. The issue is, I want the table to disappear when the second button is clicked and show the contents of the second button immediately after clicking it once, rather than having to click ...

The system does not acknowledge "ENVIRONMENT" as a command that can be executed either internally or externally, or as a batch file that can be

While running my Next.js application, I encountered the following error in a script: "scripts": { "dev: "ENVIRONMENT=env/.env.development next dev", "check": "npm run format && npm run eslint", "e ...

Unexpected mutation of Vuex store state detected

In my view components, I have a mixin that sets the metadata for each page. I'm retrieving the default metadata using Vuex in my store. When applying the mixin to each component, I include the "metadata" data attribute and set its value to the default ...

Retrieving column values from a Datatable is limited to the first 10 rows

Trying to extract the values from column 1. I followed the instructions provided in the datatable documentation: var data = table.column( 0 ).data(); Table setup: var datatable = table.dataTable({ "scrollX" : "100%", "scrollY" ...

The ng-options loop in the array is unable to locate the specified value

In my C# controller, I generate a list and translate it to Json for Angular to receive at the front end. However, when using ng-options to loop through this array in order to get the array value, I always end up with the index instead. <select class="s ...

Utilize Material UI AutoComplete in React to showcase a variety of choices in a list and capture various selections in the form state, including multiple values

I'm looking to implement Autocomplete in a way that it saves a specific property of an object in the form state and displays a different property in the autocomplete options list. For instance, if we have the following option list: [ { gender_name ...

The React Material Component stubbornly resists being horizontally aligned in the Code Sandbox

Currently, I am working on getting my Material design to function properly within the CodeSandbox environment. One issue I am encountering is attempting to center it horizontally. As of now, it appears like this: To make it easier to identify its locati ...

Issues with ng-click functionality in MVC partial view

I am currently working on a single page application that utilizes angular.js and MVC. Within the application, there are two partial views being called: Menu Accounts The Menu partial view loads successfully. However, I am encountering an issue with the ...