22: Store Todos Persistent

Let's save the todo list in localStorage and make it persistent.

  1. Define StorageClerk class as module to manage localStorage. It has two static method `fetch` and `save`.
  2. Replace default todos state with result of StorageClerk#fetch.
  3. Define watcher for todos with x-watch directive.

  <script src="https://x-ninja.org/assets/js/flux._.js"></script>
  
  <script>
    class StorageClerk {
      static fetch () {
        const storageJSON = localStorage.getItem(this.STORAGE_KEY)
        return storageJSON
          ? JSON.parse(storageJSON) || []
          : []
      }

      static save (todos) {
        localStorage.setItem(
          this.STORAGE_KEY,
          JSON.stringify(todos)
        )
      }
    }

    StorageClerk.STORAGE_KEY = 'todos-xninjajs'
  </script>
  
  <title>TODOs @x-ninja</title>
</head>
<body>
  <section class="todoapp"
    x-state="{
      todos: [],
      todos: StorageClerk.fetch(),
      editingTodoIndex: -1,
      visibility: 'all',
    }"




    x-watch="{
      todos (_, newState, oldState) {
        StorageClerk.save(newState.todos)
      }
    }"
  ::>



  </section>
</body>
</html>