Fork me on GitHub

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


@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.


But basically it’s trivial to implement yourself.

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

(defn ls-get
  (some->> (.getItem js/localStorage k)

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

 (fn [cofx k]
   (assoc cofx :local-storage-value (ls-get k))))



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


Thank you for the example


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.


@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))

 (fn [cofx k]
   (assoc-in cofx [:local-storage k] (ls-get k))))

 (fn  [k]
   (ls-remove! k)))

 (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]}