priortt
priortt

Reputation: 129

List not updating entirely after an entry from array is removed in Vue

I have a list of small cards (all have the same structure) which display data from the store and generate some parts inside of them. When a card is removed, all cards below it 'slide up' and the data moves with them but the images and the title(both generated inside of each card) stay where they were before creating a mess of wrongly labelled cards (i.e. the cards are removed correctly but image data stays where it was before). After some testing I believe it is the image that is not updating.

At the moment I assign the key-value pairs inside of data but I reckon maybe I should do it using computed() or some other hook to trigger changes whenever a card is removed.

Here are the code snippets:

Parent component

<template>
...

<div v-for="card in cards" :key="card.code">
    <Card :card="card" />
</div>

...
</template>
<script>
import store from './store';
import Card from './Card';
...
components: {
    Card
},
data() {
    return {
        cards : store.state.cards, 
    }
}

...
</script>

Child component (Card.vue)

<template>
...

<img :src="image.imgSrc" />
<div>
    <h3>{{ image.imgName }}</h3>
    <div>
        <button @click="removeCard(card[5])">Remove Card</button>
    </div>
</div>

...

<div v-for="data in card" :key="data.title">
    <p class="m-0">{{ data.title }}</p>
</div>

...
</template>

<script>
import store from "./store";

export default {
...

  props: {
    card: Array,
  },
  data() {
    return {
      removeCard: store.removeCard,
      cards: store.cards,
      image: {
          imgSrc: `https://somelink.com/image/${this.card[5].toLowerCase()}.png`,
          imgName: this.card[4],
      },
    };
  },
</script>

removeCard from state

removeCard(id) {
    const { cards } = state;
    cards.splice(cards.findIndex(card => { return card[5] === id; }), 1);
  }

I obviously removed a whole lot of logic for the sake of simplicity but I think it should be relatively obvious what is going on. cards is an array of this structure:

[
  [ {Object}, {Object}, {Object, {Object}, 'WholeName1', 'CardsUniqueCode1' ],
  
  [ {Object}, {Object}, {Object, {Object}, 'WholeName2', 'CardsUniqueCode2' ],

  ...
]

I hope it makes sense and please let me know if there is anything I could to explain further.

Upvotes: 2

Views: 125

Answers (1)

Helper function
Helper function

Reputation: 230

You should probably use mapState from vuex to map store.state.cards to a computed property. Example:

// parent component

import { mapState } from "vuex";

...
{...
  computed: {
   ...mapState(["cards"])
  }
}

Upvotes: 1

Related Questions