Skip to content

Instantly share code, notes, and snippets.

@export-mike
Created June 18, 2018 08:22
Show Gist options
  • Select an option

  • Save export-mike/3df33844c5351c5df802cd99459f20c4 to your computer and use it in GitHub Desktop.

Select an option

Save export-mike/3df33844c5351c5df802cd99459f20c4 to your computer and use it in GitHub Desktop.

Revisions

  1. export-mike created this gist Jun 18, 2018.
    68 changes: 68 additions & 0 deletions index.js
    Original 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);
    }