Home > Mobile >  How can I save an object's methods when storing it to localStorage via JSON?
How can I save an object's methods when storing it to localStorage via JSON?

Time:08-31

I finished building a to-do app and I'm trying to get it to work with localStorage. So far I have managed to save everything I wanted to localStorage (the array that holds all the projects, the array holding all the to-dos, and even the class' static property representing the instance count), but I don't know how to save the methods.

Each to-do class has a method for deleting an item. The methods gets added to a corresponding button via event listeners (when the to-dos get displayed on the page), and after I refresh the page, the buttons loose the functionality (i.e. the methods aren't saved & fetched from localStorage and I get an error saying "... is not a function".

Here's how the to-do class looks like as an example:

    class ToDo {
  static keyCount = JSON.parse(localStorage.getItem("todoCount")) || 0;
  constructor(title, project, dueDate, text) {
    this.title = title;
    this.dueDate = dueDate;
    this.text = text;
    this.done = false;
    this.key = ToDo.keyCount  ;
    this.project = project;
  }

  saveCountToLocal() {
    localStorage.setItem("todoCount", JSON.stringify(ToDo.keyCount));
  }

  deleteItem(item) {
    toDoList.splice(toDoList.indexOf(item), 1);
  }

"saveCountToLocal" is a function that I use every time an instance is created, in order to actually save the count, and it works just fine, whereas "deleteItem" doesn't.

The method that I need to save is "deleteItem". I know JSON doesn't save the methods, so what could be a workaround for this?

CodePudding user response:

Saving a function to local storage is really cursed, definitely not a good idea. From the looks of it deleteItem doesn't need to be a class method so remove it from the ToDo class and have it as a separate function.

class ToDo {
  // Omitted for brevity
}

function deleteItem(item) {
  toDoList.splice(toDoList.indexOf(item), 1);
}

You really shouldn't save a function to local storage, it's not safe and it's going to be a pain to maintain; but if you really want to save a function to local storage, I guess you could do something like this (untested):

const todo = new ToDo(...)
const json = JSON.stringify({ ...todo, deleteItem: todo.deleteItem.toString() })
localStorage.setItem("todo", json)

const parsed = JSON.parse(localStorage.getItem("todo"))
const deleteItemText = RegExp(/{(.*)}/s).exec(parsed.deleteItem)[1]
parsed.deleteItem = Function(deleteItemText).bind(parsed)
  • Related