Updating components reactively in Vue.js when a click event occurs

I have a dilemma with my component that allows users to add or remove an item from their favorites. While the functionality works smoothly, there is no visual indication for the user to know whether the item has been added to favorites or not. Currently, I display a filled star icon if the item is favorited and an empty one if it is not. How can I make this interaction reactive? I want the icon to change its appearance when clicked on by the user.

Below is a snippet of my code:

Component:

<template>
 <span :class="isFavorite
            ? 'mdi mdi-star favorite'
            : 'mdi mdi-star-outline'"
    class="favorite-item-icon"
    @click="isFavorite ? deleteFromFavoriteItems(itemId) : addToFavoriteItems(itemId)">
 </span>
</template>

<script>
 export default {
  import { mapGetters, mapActions } from 'vuex';

  props: ['itemId', 'isFavorite'],
  methods: {
    ...mapActions(['addToFavoriteItems', 'deleteFromFavoriteItems']),
  },
};
</script>

The component within a v-for loop list in the parent component:

...
 <favorite-label :itemId="item.id" :isFavorite="item.is_favourite" />
...

In my Vuex store:

addToFavoriteItems({ commit }, itemId) {
  http
    .post(`${config.api}api/v1/items/favourite-save`, {
      item_id: itemId,
    });
deleteFromFavoriteItems({ commit }, itemId) {
  http
    .post(`${config.api}api/v1/items/favourite-delete`, {
      item_id: itemId,
    });

Answer №1

To update the store with the new item from the server, you can do something like this:

$post(..., { item_id: itemId }).then(function(response) {
  this.$store.commit('items/SET_ITEM', response.data)
})

The items/SET_ITEM mutation will iterate through the items in the current array and update the item if the id matches.

let itemToUpdate = this.items.forEach(function(i) {
  if (i.id === item.id) {
    i = item
  }
})

This will then mutate the store correctly, triggering a re-render of the view with the updated isFavorite calculation in place.

Alternatively, if the itemId being passed does not require any changes from the server, you can simply pass it along like this:

$post(..., { item_id: itemId }).then(function() {
  this.$store.commit('items/UPDATE_FAVORITE', { item: itemId })
})

Then, you just need to add a mutation that toggles the favorite status:

this.items.forEach(function(i) {
  if (i.id === item) {
      i.is_favorite = !i.is_favorite
  }
})

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

Interacting Shadows with BufferGeometry in react-three-fiber

I've been working on my custom bufferGeometry in react-three-fiber, but I can't seem to get any shadows to show up. All the vertices, normals, and UVs are set correctly in my bufferGeometry, and I even tried adding indices to faces, but that just ...

What is the best way to eliminate the content of an element using javascript/typescript?

The progress bar I'm working with looks like this: <progress class="progress is-small" value="20" max="100">20%</progress> My goal is to use javascript to remove value="20", resulting in: <progre ...

Troubleshooting: 404 Error When Trying to Send Email with AJAX in Wordpress

In the process of creating a unique theme, I encountered an interesting challenge on my contact page. I wanted to implement an AJAX function that would allow me to send emails directly from the page itself. After conducting some research, I managed to find ...

Exploring touch interactions using D3.js and TUIO

I'm currently facing a challenge with implementing multi-touch functionality and the d3.slider in my D3 Map. You can see the current state of my project in this video. With the d3 slider, I can spawn points and navigate around the map using touch even ...

Is there a reason behind why this functionality is only applicable to a class component and not a functional one?

Essentially, I am working with multiple buttons and aiming for the user to be able to select more than one button at a time. I attempted to achieve this using a functional component by storing the button states as objects with the useState hook. While the ...

At what point is it necessary to generate a new vertex array object when sketching numerous objects?

I'm embarking on a game development project using WebGL. Currently, I have three textures in my arsenal- one for letters used in the font, another for character sprites, and a tilemap texture for the world. With these large textures at hand, I find m ...

When executing the app.delete function, the req.body is found to be empty

I've encountered an issue when trying to send JSON data in an $http Delete call, as the req.body returned is coming back as an empty JavaScript object. Below is my $http delete call where "scenario" is a json object: //Deletes the item from the data ...

Issues with the functionality of jQuery event functions

My webpage retrieves content from a database using jQuery and AJAX. There are various processes on the page such as adding new content, editing, and deletion, all of which use AJAX. However, I am experiencing issues with event functions like click and mous ...

Is it possible to launch a React application with a specific Redux state preloaded?

Is there a way to skip navigating through a bulky frontend application in order to reach the specific component I want to modify? I'm curious if it's feasible to save the redux store and refresh my application after every code alteration using t ...

Issue with jQuery 'on' event not triggering following 'load' event

I am facing an issue on a page where similar events occur but when new content is loaded halfway through, most of the jQuery functionalities stop working. The scenario involves answering questions in a 'game' format using AJAX calls. Once all que ...

React Jodit Editor experiencing focus loss with onchange event and useMemo functionality not functioning properly

I'm currently working on a component that includes a form with various inputs and a text editor, specifically Jodit. One issue I've encountered is that when there are changes in the Jodit editor's content, I need to retrieve the new HTML va ...

Exploring the world of jQuery and Ajax: Experimenting with implementing a POST method through Ajax and retrieving the response in HTML

Hey guys, I'm currently attempting to set up a basic HTML post method using Ajax. Take a look at the code snippet below: <?PHP function fetchInstagramData($url) { $ch = curl_init(); curl_setopt_array($ch, array( CURLOPT_URL => ...

The standard outcome when searching in the v-data-table

I am working on a v-data-table with a search feature, and I want to display a default row when no search results are found. For instance, if my table lists "Apples", "Oranges", "Pears" and I search for "Peaches", I want the "Apples" row to be displayed in ...

Having trouble getting my subarrays to push correctly into the parent array in ReactJS. What am I doing wrong

I am currently working on implementing the bubblesort algorithm using ReactJS. My state includes an array of 3 objects initially sorted in descending order by the 'num' property. I have a button on my interface that triggers the bubblesort functi ...

Access a JSON response within an HTML/JavaScript document

Can the scenario below be achieved? Here is the ajax response I received: HTML <body> <input type="text"></input> <div id="trydiv"></div> </body> JS $.ajax({ type: "POST", url: "json.php", ...

What is the best way to transform a JSON object from a remote source into an Array using JavaScript?

Attempting to transform the JSON object retrieved from my Icecast server into an array for easy access to current listener statistics to display in HTML. Below is the JavaScript code being used: const endpoint = 'http://stream.8k.nz:8000/status-json ...

Is there a way to determine if a click occurred outside of a div without relying on stopPropagation and target event?

My goal is to track multiple div elements and determine if a click occurs outside of any of these divs. I am looking for a solution that does not involve using stopPropagation or event.target as they have negative effects. Is there an alternative method to ...

I'm facing issues with Angular commands not functioning properly even after installing the Angular CLI and configuring the

Every time I attempt to create a new project using Angular CLI by typing: ng n app I encounter the following error message: C:\Users\Venkateshwarn M\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng: ...

Loading the Facebook JavaScript SDK asynchronously using React and Redux

I have a process that involves loading a JavaScript SDK, which looks like this: class Facebook{ constructor(){ window.fbAsyncInit = () => { FB.init({ appId : 'myappID', ...

Whenever text is present, the sides of my box model, constructed using HTML5 and CSS3, are always pushed downward

When I add extra text to the body of my homepage, it causes a distortion and pushes down the sidebar and advertising boxes on the side. I'm working on this project for class and even though I've asked my teacher for help, she says the code is fin ...