Skip to content

Instantly share code, notes, and snippets.

@Janiczek
Last active August 29, 2015 14:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Janiczek/64067b8a5c22de25cc8a to your computer and use it in GitHub Desktop.
Save Janiczek/64067b8a5c22de25cc8a to your computer and use it in GitHub Desktop.
Keeping state between Figwheel reloads
;;;;;;;; actually, (defonce state (new-state)) solves all of this.
;;;;;;;; thanks @bhauman for pointing this out!
;;;;;;;; https://twitter.com/bhauman/status/508328343201005568
;;;;;;;; ---------------------------------------------------------
;; How to keep state atom between Figwheel reloads?
(ns example
(:require [cljs.reader :refer [read-string]]))
(defn new-state []
{:counter 0})
(def local-storage-key "example-state")
(defn save-to-local-storage! [new-state]
;; for use in add-watch inner function
(let [serialized (pr-str new-state)]
(.setItem js/localStorage local-storage-key serialized)))
(defn load-from-local-storage! []
(when-let [state (.getItem js/localStorage local-storage-key)]
(read-string state)))
(let [loaded-state (load-from-local-storage!)]
(defonce state (atom
(if (nil? loaded-state)
(new-state)
loaded-state))))
(add-watch state :state
(fn [_ _ _ new-state]
(save-to-local-storage! new-state)))
(fw/watch-and-reload
;; ... maybe :jsload-callback for React's render-component etc.
)
;; With this, Figwheel will keep your state atom between reloads!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment