Day 25: Banish Boredom: Day 2
Lesson 1: Banish Boredom: 5
When we click delete we want to remove that activity from the saved activities list, then rerender the list so that the activity is no longer on screen.
Add this function to your JavaScript file:
1const deleteActivity = (key) => { 2 const savedActivitiesString = localStorage.getItem("activities"); 3 4 const savedActivities = JSON.parse(savedActivitiesString) ?? []; 5 6 const updatedActivities = savedActivities.filter( 7 (activity) => activity.key !== key 8 ); 9 10 localStorage.setItem("activities", JSON.stringify(updatedActivities)); 11};
Then change the onClick
handler for the delete button to this:
1newCardDeleteButton.onclick = () => { 2 deleteActivity(savedActivity.key); 3};
As we add the onclick
handler to the button in the savedActivities.forEach
loop we know the key for that activity. The key is a unique identifier for this activity, so we can use that to identify which activity we need to remove from the list.
Then in deleteActivity
you should see a familiar pattern. We read the activities from LocalStorage, make a change and then save the list back to LocalStorage.
To remove the activity from the list we simply use the array .filter
method to keep all the items that don't have the key
we want to delete, then get rid of any that have the same key
.
Click delete on an item and then refresh the page, see how it's now gone!?
So we know it's working, now we need to update the user interface without the refresh.