Reputation: 35
I'm new to working with localStorage in Javascript. I'm doing a CRUD of todo's (I'm working with jsonplaceholder to get the todo's list). The problem is that I have to get the specific element while clicking the button(delete/edit) of that element. I attach an image to see how I have rendered my elements:
What I want here is, when I click the "Delete" button element I want to get that specific element to apply a .splice
and delete that element from the localStorage array.
After that: how can I edit the specific element when I click "Edit".
PS. If works, I'm working with Vue.js
PS2. IF you need more information about the code, please let me know
Best regards!
Upvotes: 0
Views: 977
Reputation: 86
As you didn't provide any code, so I have provided my possible guess to you. The code is given below:
<template>
<div>
<ul>
<li v-for="(item, index) in list" :key="index">
<span>{{ item }}</span>
<button @click="deleteFromList(index)">Delete</button>
<button @click="editItem(index)">Edit</button>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
list: ["john", "doe", "jane"]
};
},
methods: {
deleteFromList(index) {
this.list.splice(index, 1);
}
}
};
</script>
enter code here
Please visit this link to know briefly. https://codepen.io/jacob-king/pen/PpGLQG
Upvotes: 1
Reputation: 3159
The usual structure of each of the todo
sent from jsonplaceholder is of the following format:
{
completed: false,
id: 1,
title: "delectus aut autem",
userId: 1
}
If you fetch from https://jsonplaceholder.typicode.com/todos
, then you will get an array of the above mentioned objects.
Now to answer your question, the simplest way is to store the whole array of objects that you display in screen into a single key in localstorage. Example:
// store the fetched todos into a state called `todos`
localStorage.setItem("todos", todos);
When you delete a particular todo, you can modify the state todos
and again invoke localStorage.setItem("todos", todos);
, such that your localStorage is updated with latest data.
Similar logic can applied while you edit.
Also to answer your question on how to edit a specific element on clicking Edit
button, just find the object from array of todo objects and update your todos
state:
const todo = todos.find(todo => todo.id == currentlySelectedTodoId);
// rest of the logic
Upvotes: 0