Fork me on GitHub
#re-frame
<
2018-09-22
>
sveri11:09:32

Hi, what would be the idiomatic way to store the whole database in localstorage, or, just some parts of it? Any advices / ideas?

valtteri11:09:20

@sveri if your db contains just data which serializes nicely you can dump it into localstorage under some key using pr-str and read it from there with read-string. I’m not sure how idiomatic this is but that’s what I’m doing.

valtteri11:09:56

But basically it’s trivial to implement yourself.

(defn ls-set! [k v]
  (.setItem js/localStorage k (pr-str v)))

(defn ls-get
  [k]
  (some->> (.getItem js/localStorage k)
           (reader/read-string)))

(defn ls-remove!
  [k]
  (.removeItem js/localStorage k))

(re-frame/reg-cofx
 :get-local-storage-value
 (fn [cofx k]
   (assoc cofx :local-storage-value (ls-get k))))

....etc

sveri11:09:33

@valtteri ok, so you are using a co-effect, thats what I wanted to know 🙂

sveri11:09:36

Thank you for the example

valtteri12:09:46

Yes I use cofx so local storage values can be injected into event handlers. For setting the values the most idiomatic thing would probably be reg-fx.

valtteri13:09:49

@sveri Actually I just noticed that my own implementation was a bit half-assed and I fixed it. This is now my whole local storage namespace

(defn ls-set! [k v]
  (.setItem js/localStorage (pr-str k) (pr-str v)))

(defn ls-get [k]
  (when-let [s (.getItem js/localStorage (pr-str k))]
    (reader/read-string s)))

(defn ls-remove! [k]
  (.removeItem js/localStorage k))

(re-frame/reg-cofx
 ::get
 (fn [cofx k]
   (assoc-in cofx [:local-storage k] (ls-get k))))

(re-frame/reg-fx
 ::remove!
 (fn  [k]
   (ls-remove! k)))

(re-frame/reg-fx
 ::set!
 (fn  [[k v]]
   (ls-set! k v)))
So retrieving values happens via cofx for easy injection into events with (re-frame/inject-cofx ::local-storage/get :some-key) Setting and removing values happens by defining them as effects in the effects map.
{:db ...
 ::local-storage/set! [key value]}