Created
June 18, 2018 08:22
-
-
Save export-mike/3df33844c5351c5df802cd99459f20c4 to your computer and use it in GitHub Desktop.
Revisions
-
export-mike created this gist
Jun 18, 2018 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,68 @@ import * as Unstated from 'unstated'; import debounce from 'lodash.debounce'; import clonedeep from 'lodash.clonedeep'; import { Alert } from 'react-native'; import AsyncStorage from '../AsyncStorage'; const noop = () => {}; //set FS storage limit for android: https://codedaily.io/tutorials/4/Increase-Android-AsyncStorage-Size-in-React-Native export class Container extends Unstated.Container { debounce = 800; constructor({ key } = {}) { super(); this.key = key; if (!key) { if (process.env.NODE_ENV === 'development') { console.warn( 'Storage for Container not enabled, provide a name property' ); } this.setState = super.setState; // disable override saving } else { this.restoreState(this.key) .then(state => { if (state) { super.setState(state); } }) .catch(e => { console.warn('Error hydrating from storage', e); }); } } setState(state, callback = noop) { if (!this.initialState) { this.initialState = clonedeep(this.state); } let newState = state; if (typeof state === 'function') { newState = state(this.state); } super.setState(newState, callback); this.setItem(this.key, newState); } setStateSkipPersist(state, callback = noop) { super.setState(state, callback); } restoreState = async () => { try { const result = await AsyncStorage.getItem(this.key); if (!result) return this.state; return JSON.parse(result); } catch (e) { console.log(e); console.warn(`Error getting Item to restore State ${this.key}`, e); return this.state; } }; setItem = debounce(async (key, state) => { try { await AsyncStorage.setItem(key, JSON.stringify(state)); } catch (e) { if (e.message.includes('database or disk is full')) { Alert.alert('Disk space is full, offline features will be degraded'); } console.warn(`Error Setting Item ${key}`, e, state); } }, this.debounce); }