Last active
August 29, 2015 14:06
-
-
Save Janiczek/64067b8a5c22de25cc8a to your computer and use it in GitHub Desktop.
Keeping state between Figwheel reloads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;;;;;;;; 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