30 Days Of JavaScript

Day 29: Mopping up

Lesson 2: Modules 2

What would be really good is if we can move all the LocalStorage stuff out.

That's a little more involved, let's make a class.

Create a new file called dataStore.js and add this code:

1export class DataStore {
2  constructor(saveKey) {
3    this.saveKey = saveKey;
4  }
5
6  getActivities() {
7    const savedActivitiesString = localStorage.getItem(this.saveKey);
8
9    return JSON.parse(savedActivitiesString) ?? [];
10  }
11
12  addActivity(newActivity) {
13    const savedActivitiesString = localStorage.getItem("activities");
14
15    const savedActivities = JSON.parse(savedActivitiesString) ?? [];
16
17    savedActivities.push(newActivity);
18
19    localStorage.setItem("activities", JSON.stringify(savedActivities));
20  }
21
22  deleteActivity(key) {
23    const savedActivitiesString = localStorage.getItem("activities");
24
25    const savedActivities = JSON.parse(savedActivitiesString) ?? [];
26
27    const updatedActivities = savedActivities.filter(
28      (activity) => activity.key !== key
29    );
30
31    localStorage.setItem("activities", JSON.stringify(updatedActivities));
32  }
33}

Then back in main.js add this line below your first import:

1import { DataStore } from "./dataStore.js";

Then right below that create an instance of that class with:

1const dataStore = new DataStore("activities");

Now replace this code in deleteActivity in main.js:

1const savedActivitiesString = localStorage.getItem("activities");
2
3const savedActivities = JSON.parse(savedActivitiesString) ?? [];
4
5const updatedActivities = savedActivities.filter(
6  (activity) => activity.key !== key
7);
8
9localStorage.setItem("activities", JSON.stringify(updatedActivities));

With:

1dataStore.deleteActivity(key);

Then in onLikeClicked replace:

1const savedActivitiesString = localStorage.getItem("activities");
2
3const savedActivities = JSON.parse(savedActivitiesString) ?? [];
4
5savedActivities.push(currentActivity);
6
7localStorage.setItem("activities", JSON.stringify(savedActivities));

With:

1dataStore.addActivity(currentActivity);

Finally in renderList replace:

1const savedActivitiesString = localStorage.getItem("activities");
2
3const savedActivities = JSON.parse(savedActivitiesString) ?? [];

With:

1const savedActivities = dataStore.getActivities();

Now run your code and it will be exactly the same as before. Except your code is organized a little better 😊

You can find this code on on a branch of the Banish Boredom GitHub repo called code-splitting.

Outline

Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co