This page is not created by, affiliated with, or supported by Slack Technologies, Inc.
2018-09-22
Channels
- # 100-days-of-code (1)
- # beginners (51)
- # carry (1)
- # cider (10)
- # clojure (71)
- # clojure-conj (4)
- # clojure-dev (9)
- # clojure-italy (3)
- # clojure-nl (2)
- # clojure-russia (8)
- # clojure-uk (16)
- # clojurescript (42)
- # cursive (4)
- # datomic (2)
- # emacs (8)
- # figwheel-main (7)
- # fulcro (20)
- # hyperfiddle (5)
- # jobs (2)
- # off-topic (16)
- # om-next (4)
- # onyx (9)
- # powderkeg (1)
- # re-frame (8)
- # reagent (17)
- # reitit (41)
- # robots (6)
- # rum (1)
- # shadow-cljs (54)
- # testing (3)
- # tools-deps (19)
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.
There are a couple of utils listed here https://github.com/Day8/re-frame/blob/master/docs/External-Resources.md#effect-and-coeffect-handlers
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
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))
(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]}