Created
June 18, 2018 08:22
-
-
Save export-mike/3df33844c5351c5df802cd99459f20c4 to your computer and use it in GitHub Desktop.
Unstated Offline Container
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 characters
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); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
with AsyncStorage having a different implementation for Android to avoid FS Storage limits.
IOS:
Storage using react-native AsyncStorage