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

Adjusting value of one input field according to the content of another text field in an

Just starting out with Angular and I am looking to dynamically change the value of a hidden input field called 'cc_card' based on the first digit entered in another input field called 'cc_number'. For example, if the user enters 5 in &a ...

AngularJS flip card animation

Exploring the new AngularJS method for animations during page transitions, I am keen on integrating a card flip effect (resembling http://jsfiddle.net/nicooprat/GDdtS/) body { background: #ccc; } .flip { -webkit-perspective: 800; width: 400px; height: ...

Is there a way to add a price to an object in JavaScript?

Purchasedata.find(function(err, purchasedatas) { if (err) { return handleError(res, err); } var totalprice = 0; for (var i = 0; i < purchasedatas.length; i++) { findProduct(i, function(i, price) { }); } ...

Unable to access the computed attribute (array)

My goal is to create a computed property called 'displayImages' that returns an array. The default value of the 'selected' property is set to 0. This property changes based on mouseover and click events. However, when I try to access t ...

Interactive sidebar component with navigation and animated section markers

For weeks, I've been attempting to create a navigation sidebar similar to the ones shown in these images: Even though getbootstrap.com/components offers appealing navigation sidebars, I have not found a built-in component in their library. This has m ...

Using JQuery to properly introduce a script in the body of a webpage

<script> /* adjust #splash-bg height based on #meat element */ $(window).on('load',function(){ var splashbgHeight = $("#meat").css("top"); $("#splash-bg").css("height",splashbgHeight); $(w ...

Unable to reset input fields in Javascript problem persists

Check out my JSFiddle demo: http://jsfiddle.net/kboucheron/XVq3n/15/ When I try to clear a list of items by clicking on the "Clear" button, I want the text input field to be cleared as well. However, I am unable to achieve this functionality. <input t ...

Deactivating controls while displaying the loading bar in AngularJS

I'm currently working on a web application using AngularJS. I want to incorporate a loading bar to signify long data load times from the server. To replicate heavy data loads, I am utilizing $timeout to trigger the loadbar when the operation begins a ...

Updating array properties in a JSON object using a foreach loop will automatically update all corresponding keys

Having a slight headache working on this particular issue. My aim is to construct an array of JSON objects using a foreach loop, and everything is functioning perfectly except for one property. The problematic property is actually an array that gets update ...

What's the best way to display a bootstrap modal window popup without redirecting to a new page?

I am having trouble implementing a modal window that will display validation errors to the user when they submit a form. Currently, the window is opening as a new view instead of overlapping the existing form's view. How can I adjust my code so that t ...

What methods can be used to block the input of non-numeric characters in a text field?

I stumbled upon this particular inquiry. Although, the majority of responses involve intercepting key presses, checking the key code, and halting the event if it does not match an acceptable key code. However, there are some issues with this approach. ...

Please be patient for the PayPal script to load on the nextjs page

I've encountered an issue with my code that is meant to display PayPal buttons <Head> <script src="https://www.paypal.com/sdk/js?client-id=KEY"></script> </Head> The PayPal buttons are loaded within the ...

Reset an Angular service's public variable

I recently started working with Angular and encountered an issue that I couldn't find a solution for on Google or Stack Overflow. I believe my problem lies in not knowing what to search for. Here is the code snippet causing trouble: JSFiddle HTML &l ...

Unlock the power of AJAX in your WordPress site

I've been exploring the realm of Javascript and AJAX lately. I feel like I'm so close to getting it right, but there's something off with how I'm integrating WordPress ajax functions. I've spent a lot of time going through the docu ...

What is the most efficient approach to completing everyday tasks directly in a Vuex store?

Currently, I am working on making API calls from within a Vuex store action object. Here's an example of one of my actions: /** * Check an account activation token * */ [CHECK_ACTIVATION_TOKEN] ({commit}, payload) { Api.checkActivationToken(payl ...

What is the method used by React or Next to prevent the <a> tag from refreshing the page while still loading content?

I'm currently diving into the world of NextJS and utilizing the Link component from the 'next/link' package. One thing that has been puzzling me is how the <Link> component ultimately renders an <a> tag with a href='/tosomew ...

How to store data retrieved with $http.get in AngularJS into a variable

I am attempting to assign data retrieved from $http.get to a variable in my controller. $http.get(URL).success(function (data) { $scope.results = data; console.log('results within $http.get :'+ $scope.results); }); console.lo ...

What is the best way to implement CSS in this JavaScript Fetch code in order to manipulate the text's position and font style

Hello, I am just starting out with JS. Is there a way for me to customize the position and font of text in this JS Fetch function using CSS? Any help will be greatly appreciated. let file = 'art.txt'; const handleFetch = () => { fe ...

Integrating Next.js with a authentication provider and a Redux provider

During the development of my Next js project, I incorporated Next auth using import {Provider} from 'next-auth/client' to wrap the <Component /> in _app.js. However, I also want to integrate Redux into the project. This involves importing ...

Avoiding the default action to submit AJAX form data won't result in any changes to the front end?

Currently, I am working with Flask and have utilized JavaScript to prevent default behavior in order to send all the necessary data through an AJAX request. However, I am facing an issue where although my view contains all the data (verified by console out ...