Skip to content

Instantly share code, notes, and snippets.

@mfikes
Created May 7, 2018 19:05
Show Gist options
  • Save mfikes/4ac767c0de05cc127a42c14707723ec4 to your computer and use it in GitHub Desktop.
Save mfikes/4ac767c0de05cc127a42c14707723ec4 to your computer and use it in GitHub Desktop.
(ns storage-fx
(:require
[cljs.reader :refer [read-string]]
[re-frame.core :refer [reg-fx dispatch]]))
(def react-native (js/require "react-native"))
(def async-storage (.-AsyncStorage react-native))
(defn save-item
[{:keys [key data on-success on-failure]}]
(.setItem async-storage (pr-str key) (pr-str data)
(fn [error]
(if-not error
(dispatch on-success)
(dispatch (conj on-failure error))))))
(defn load-item
[{:keys [key on-success on-failure]}]
(.getItem async-storage (pr-str key)
(fn [error result]
(if-not error
(try
(let [data (read-string result)]
(dispatch (conj on-success data)))
(catch :default e
(dispatch (conj on-failure e))))
(dispatch (conj on-failure error))))))
(defn remove-item
[{:keys [key on-success on-failure]}]
(.removeItem async-storage (pr-str key)
(fn [error]
(if-not error
(dispatch on-success)
(dispatch (conj on-failure error))))))
(reg-fx :storage/save-item save-item)
(reg-fx :storage/load-item load-item)
(reg-fx :storage/remove-item remove-item)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment