Skip to content

Instantly share code, notes, and snippets.

@olivergeorge
Last active May 7, 2018 22:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olivergeorge/6f740bd63d996c31d87de952d51882d1 to your computer and use it in GitHub Desktop.
Save olivergeorge/6f740bd63d996c31d87de952d51882d1 to your computer and use it in GitHub Desktop.

Storing data in the app

Without a persistent data store our React Native app would lose all state if killed and restarted.

React Native solves this by providing a simple storage system that is global to the app called AsyncStorage.

Tradeoffs

It is recommended that you use an abstraction on top of AsyncStorage like sunnylqm/react-native-storage but for now a few helper functions seem to suffice. Here's an alternative approach.

Effects

Our handlers will want to save, load and remove items from storage.

References

Based on Mike Fike's gist

Alternative approach using react-native-storage

(ns future-app.effects.storage-effects
(:require [future-app.rn-api :as rn-api]
[cljs.reader :refer [read-string]]
[clojure.string :as string]
[re-frame.core :as re-frame]))
(def AsyncStorage (.-AsyncStorage rn-api/ReactNative))
(defn save-item
[{:keys [key data on-success on-failure]}]
(.setItem AsyncStorage (pr-str key) (pr-str data)
(fn [error]
(if-not error
(when on-success (re-frame/dispatch on-success))
(when on-failure (re-frame/dispatch (conj on-failure error)))))))
(defn load-item
[{:keys [key on-success on-failure]}]
(.getItem AsyncStorage (pr-str key)
(fn [error result]
(if-not error
(try
(let [data (read-string result)]
(when on-success (re-frame/dispatch (conj on-success data))))
(catch :default e
(when on-failure (re-frame/dispatch (conj on-failure e)))))
(when on-failure (re-frame/dispatch (conj on-failure error)))))))
(defn remove-item
[{:keys [key on-success on-failure]}]
(.removeItem AsyncStorage (pr-str key)
(fn [error]
(if-not error
(when on-success (re-frame/dispatch on-success))
(when on-failure (re-frame/dispatch (conj on-failure error)))))))
(re-frame/reg-fx :storage/save-item save-item)
(re-frame/reg-fx :storage/load-item load-item)
(re-frame/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