Skip to content

Commit

Permalink
[added] NativeHistory -wip
Browse files Browse the repository at this point in the history
  • Loading branch information
mjackson committed Jun 19, 2015
1 parent 4759961 commit bf6f9a7
Showing 1 changed file with 69 additions and 0 deletions.
69 changes: 69 additions & 0 deletions modules/NativeHistory.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { AsyncStorage, PropTypes } from 'react-native';
import MemoryHistory from './MemoryHistory';
import Location from './Location';

var { bool, string } = PropTypes;

function encodeState(state) {
return JSON.stringify(state);
}

function decodeState(string) {
var state;
try {
state = JSON.parse(string);
} catch (error) {
// Invalid JSON in AsyncStorage for some reason. Ignore it.
state = {};
}

// Make sure we have a real Location.
if (state && state.location) {
var { location } = state;
state.location = new Location(location.path, location.query, location.navigationType);
}

return state;
}

/**
* A history implementation for React Native environments that
* supports persistence across the application lifecycle using
* the AsyncStorage module.
*/
class NativeHistory extends MemoryHistory {

static propTypes = Object.assign({}, MemoryHistory.propTypes, {
storageKey: string.isRequired,
autoSave: bool.isRequired
});

static defaultProps = Object.assign({}, MemoryHistory.defaultProps, {
storageKey: '@ReactRouterNativeHistory',
autoSave: true
});

static childContextTypes = Object.assign({}, MemoryHistory.childContextTypes);

componentWillMount() {
AsyncStorage.getItem(this.props.storageKey, (error, value) => {
if (error) {
throw error; // TODO: Keep this around in state?
} else {
this.setState(decodeState(value));
}
});
}

componentDidUpdate() {
if (this.props.autoSave)
this.saveToAsyncStorage();
}

saveToAsyncStorage(callback) {
AsyncStorage.setItem(this.props.storageKey, encodeState(this.state), callback);
}

}

export default NativeHistory;

0 comments on commit bf6f9a7

Please sign in to comment.