Hi there, I'm currently working on creating a wishlist feature using local storage. The idea is that when the user clicks on the "add to wishlist" button, the item should be added to local storage and then display a "remove from wishlist" option. I attempted to achieve this using ES6's filter and find functions, but I think I may have made a mistake somewhere in my code. You can find the code at this link. Any assistance would be greatly appreciated. Thank you!
https://codesandbox.io/s/wishlist-ouuyw?file=/src/App.vue
<template>
<div id="app">
<h2>Total Selected: {{selectedEntries.length}}</h2>
<div v-for="entry in entries" :key="entry.id">
<div class="content-wrap">
<h3>{{entry.title}}</h3>
<button v-if="!checkExists" @click="addToWishlist(entry.id)">Add Wishlist</button>
<button v-else @click="removeToWishlist(entry.id)">Remove Wishlist</button>
</div>
</div>
</div>
</template>
<script>
export default {
name: "App",
data(){
return{
entries: [
{
title: 'entry one',
id: 1
},
{
title: 'entry two',
id: 2
},
{
title: 'entry three',
id: 3
},
{
title: 'entry four',
id: 4
},
{
title: 'entry five',
id: 5
},
],
selectedEntries: JSON.parse(window.localStorage.getItem("wishlistItems")) || []
}
},
computed:{
checkExists(){
return this.entries.filter(entryItem => {
this.selectedEntries.find(selectedId => {
return entryItem.id === selectedId.id
})
})
}
},
methods:{
addToWishlist(entryId){
this.selectedEntries.push({ id: entryId });
window.localStorage.setItem("wishlistItems", JSON.stringify(this.selectedEntries));
console.log("Clicked>>>", this.selectedEntries)
}
}
};
</script>
<style scoped>
.content-wrap{
display: flex;
border: 1px solid;
margin: 5px;
padding: 5px;
align-items: center;
}
.content-wrap h3{
text-transform: capitalize;
width: 30%;
}
.content-wrap button{
border: none;
padding: 10px 20px;
height: 30px;
background-color: #1d9a61;
color: #fff;
font-size: 16px;
cursor: pointer;
line-height: .7
}
</style>