Utilizing Vuex to manage the state of modal components within a list of child components

I am attempting to utilize vuex to maintain a value that controls the visibility of a modal in a child component. The parent component renders the child component multiple times in a list, but the modal consistently displays only the last item in the list. Upon inspection, I noticed that my computed modal value from the vuex state is being executed the same number of times as there are elements in the list.

Vuex state

export default function () {
  return {
    currentProduct: {},
    allProducts: [],
    editProductDialog: false
  };
}

Vuex mutations

export const setEditProductDialog = (state, editProductDialog) => {
  state.editProductDialog = editProductDialog
}

Parent component:

<div>
  <product
    v-for="product in allProducts"
    :key="product.id"
    :product="product"
  />
</div>

Child component:

<template>
<div class="row justify-start">
  <div class="col-6">
    <q-item clickable v-ripple @click="runSetEditProductDialog">
      <q-item-section avatar>
        <q-icon name="chevron_right" />
      </q-item-section>
      <q-item-section class="text-body1">{{ name }}</q-item-section>
    </q-item>
  </div>
  <q-dialog v-model="editDialog" no-backdrop-dismiss>
     ...
     ...
  </q-dialog>
</template>
...
<script>
export default {
  name: "Product",
  props: ["product"],
  data: () => ({
  }),
  methods: {
    ...mapMutations({
      setEditProductDialog: "product/setEditProductDialog"
    }),
    runSetEditProductDialog() {
      this.setEditProductDialog(true)
    },
  },
  computed: {
    ...mapState("product", ["editProductDialog"]),
    editDialog: {
      get() {
        console.log("in get")
        return this.editProductDialog;
      },
       set(value) {
        console.log("in set")
        this.setEditProductDialog(value);
      },
    },
  },
};
</script>

As mentioned earlier, the dialog consistently displays the last product component. Furthermore, the print statements in my computed section confirm that they are running the same number of times as there are elements in allProducts.

How can I effectively use vuex to manage modal state when displaying a list of components?

Answer №1

Instead of using boolean true/false, consider assigning an id:

@click="runSetEditProductDialog(product.id)"

runSetEditProductDialog(id) {
  this.setEditProductDialog(id)
},

Then, in your computed property, check if they are equal:

return this.editProductDialog === this.product.id

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

Does the html label prevent propagation from occurring?

Can anyone explain why the toggle function is not being executed when clicking inside the box with the black border, but works when clicking outside of it (although not on the checkbox)? var checks = document.querySelectorAll("ul li"); for (var i = 0 ...

Background styling for TreeItems in Material-UI's TreeView

Just recently, I encountered an interesting phenomenon while working with the following dependencies: "@material-ui/core": "4.8.3", "@material-ui/lab": "4.0.0-alpha.37" After deselecting a TreeItem and selecting another one, I noticed that there was no lo ...

The data type 'unknown' cannot be assigned to the type 'any[]', 'Iterable<any>', or (Iterable<any> & any[])

I have been working on creating a custom search filter in my Angular project, and it was functioning properly. However, I encountered an error in my Visual Studio Code. In my previous project, everything was working fine until I updated my CLI, which resul ...

The functionality of socket.io is not functioning properly on the server, resulting in a 404

I encountered errors while working on a simple socket.io project on my server. The IP address I am using is . All files are stored in public_html and can be accessed through the URL: . Here are the code snippets: <!doctype html> <html> < ...

Using v-model in Vue 3 will result in modifications to the table class in Bootstrap 5

Below is a snippet of the code I wrote: <table class="table table-striped"> <tr class="table-dark"> <th>#</th> <th>Column 1</th> <th colspan="3">Column 2</th> </tr> <tr ...

Here is a way to trigger a function when a select option is changed, passing the selected option as a parameter to the function

Is there a way to call a function with specific parameters when the value of a select element changes in Angular? <div class="col-sm-6 col-md-4"> <label class="mobileNumberLabel " for="mobilrNumber">Select Service</label> <div cla ...

Send dropdown selections to a Javascript function and convert them into an array

Within my JavaScript function, I need to pass multiple selected values from dropdown menus and store them in a JavaScript array. Each time a value is selected and sent using the onchange() function, it should be added to the array. If the same value is sel ...

Troubleshooting Limitation Problem with Bootstrap Multiselect

I recently created a multiselect dropdown menu using Bootstrap Multiselect. I successfully set a limit on the number of options that can be selected (in this case, 5), and once the limit is reached, the additional options become disabled. Everything works ...

Troubleshooting problem: Unable to restrict table selections - issue with Material UI table in React

I seem to be overlooking the simple solution here. Currently, I have a ternary on my table. If the length of the selected array is greater than a certain number, a table with disabled checkboxes is rendered. I also implement a different handleClick functio ...

Issue encountered in React 18: The value on the left side of an assignment statement must be a variable or a property that can be accessed

After upgrading my React version from 17 to 18, I encountered an error with this code: data?.area?.width=['111','220']. The error message states "The left-hand side of an assignment expression must be a variable or a property access." W ...

Limiting the usage of a command in Discord.js to one user at a time, rather than all users

I'm in the process of developing a discord.js bot and I need to implement a cooldown for a specific command. After searching several tutorials online, I found that most of them apply the cooldown to all commands (meaning all users have to wait a set ...

The Chrome file storage system saves information in files

My challenge is to save data obtained from the Chrome geolocation API into a text file using the Chrome fileSystem API. However, despite successfully creating a file, it remains empty after the process. To simplify, I attempted to add the string '1234 ...

Customize the behavior of jQuery cycle with an <a> tag

Can the jQuery cycle be accessed through a link in order to override the i variable? I've come across examples that can achieve this, but not in a scenario like this where the cycle() function is located within a variable: $(document).ready(function ...

Issue importing color palettes from JSON into Tailwind CSS

While working on my Vue.js project with Tailwind CSS, I ran into an issue. It seems that Tailwind is not picking up the custom color classes specified in my JSON configuration for 'primary', 'secondary', and 'gray'. Instead of ...

How can I verify the status of an occasional undefined JSON value?

There are times when the JSON object I'm trying to access does not exist. Error: Undefined index: movies in C:\xampp\htdocs\example\game.php In game.php, I'm attempting to retrieve it from the Steam API using this code: $ ...

Navigating with AngularJS through link redirection using anchor tags

How can I achieve smooth scrolling to a specific section using angularJS when clicking on a link? When clicking on a link like this: The page instantly redirects to the specified footer section. I want to implement an angular controller to handle this fun ...

Tips for resolving the error of encountering a forbidden and unexpected token in JSON at position 0 while using React hooks

const [forecastData, setForecastData] = useState({ forecast: []}); useEffect(() => { let ignore = false; const FETCHDATA = async () => { await fetch(forecast,{ headers : { ...

Utilizing data from a JavaScript array and merging it with basic HTML structure

Every day, a js array source on a remote server gets updated: var io = new Array(); nsi[0] = new Array('','Frank','','Factory worker','Mercedes',374.0,26.2,76,181,'',75,'Audi',1456.5,27 ...

Delete the final element from the json object

I need to extract the data from a JSON object and exclude the last element called 'week2'. Here is the object with properties like username, Geo, status, month, and week2: const response = [{ Username: "Denisse Morales", Geo: "NSU", ...

Trouble with installing Enmap due to better-sqlite3 error

For a while now, I've been struggling to get enmap installed. Despite searching the web exhaustively, I haven't come across any solutions that work for me. Every time I try npm i enmap, I consistently encounter this frustrating error: One part o ...