I am building a recipe application. I am trying to create a button that deletes a previously added recipe from Vuex with local storage. My issue is when ever I click the delete button it doesn't delete the recipe that I have selected, instead it deletes the most recent recipe that I have added to my vuex array.
This is the code to my vuex store
recipes: [
{
slug: '',
title: '',
description: '',
ingredients: [
],
method: [
]
},
{
slug: '',
title: '',
description: '',
ingredients: [
],
method: [
]
},
]
},
getters: {
},
mutations: {
loadStore() {
if(localStorage.getItem('store')) {
try {
this.replaceState(JSON.parse(localStorage.getItem('store')));
}
catch(e) {
console.log('Could not initialize store', e);
}
}
},
ADD_RECIPE (state, recipe){
state.recipes.push(recipe)
},
//This is a delete request
delete_Recipe(state, recipe){
let index = state.recipes.indexOf(recipe);
state.recipes.splice(index,1);
},
},
And this is my code in which I am trying to add a button that deletes my selected recipe
<template>
<div >
<router-link to="/">< Back</router-link>
<h1>{{ recipe.title }}</h1>
<p >{{recipe.description}}</p>
<hr />
<div >
<h3> Ingredients</h3>
<ul>
<li v-for="(ingredient, i) in recipe.ingredients" :key="i">
{{ingredient }}
</li>
</ul>
</div>
<hr />
<div >
<h3> Instructions</h3>
<ol>
<li v-for="(step, i) in recipe.method" :key="i">
<span v-html="cleanText(step)"></span>
</li>
</ol>
</div>
<button @click="deleteRecipe">Delete Recipe</button>
</div>
</template>
<script>
import $store from '../store'
export default {
setup(){
const deleteRecipe = () => {
$store.commit('delete_Recipe')
}
return {deleteRecipe}
},
computed: {
recipe(){
return this.$store.state.recipes.find(recipe => recipe.slug === this.$route.params.slug)
}
CodePudding user response:
The immediate problem is inside the delete request. When Array.indexOf
doesn't find the item inside the array, it returns -1. Array.splice(-1, 1)
removes the last item in the array.
Consider passing the index to the delete request. Better yet, give each recipe a unique ID and pass that when deleting a recipe.