Skip to content

Commit bf6f9a7

Browse files
committed
[added] NativeHistory -wip
1 parent 4759961 commit bf6f9a7

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

modules/NativeHistory.js

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import { AsyncStorage, PropTypes } from 'react-native';
2+
import MemoryHistory from './MemoryHistory';
3+
import Location from './Location';
4+
5+
var { bool, string } = PropTypes;
6+
7+
function encodeState(state) {
8+
return JSON.stringify(state);
9+
}
10+
11+
function decodeState(string) {
12+
var state;
13+
try {
14+
state = JSON.parse(string);
15+
} catch (error) {
16+
// Invalid JSON in AsyncStorage for some reason. Ignore it.
17+
state = {};
18+
}
19+
20+
// Make sure we have a real Location.
21+
if (state && state.location) {
22+
var { location } = state;
23+
state.location = new Location(location.path, location.query, location.navigationType);
24+
}
25+
26+
return state;
27+
}
28+
29+
/**
30+
* A history implementation for React Native environments that
31+
* supports persistence across the application lifecycle using
32+
* the AsyncStorage module.
33+
*/
34+
class NativeHistory extends MemoryHistory {
35+
36+
static propTypes = Object.assign({}, MemoryHistory.propTypes, {
37+
storageKey: string.isRequired,
38+
autoSave: bool.isRequired
39+
});
40+
41+
static defaultProps = Object.assign({}, MemoryHistory.defaultProps, {
42+
storageKey: '@ReactRouterNativeHistory',
43+
autoSave: true
44+
});
45+
46+
static childContextTypes = Object.assign({}, MemoryHistory.childContextTypes);
47+
48+
componentWillMount() {
49+
AsyncStorage.getItem(this.props.storageKey, (error, value) => {
50+
if (error) {
51+
throw error; // TODO: Keep this around in state?
52+
} else {
53+
this.setState(decodeState(value));
54+
}
55+
});
56+
}
57+
58+
componentDidUpdate() {
59+
if (this.props.autoSave)
60+
this.saveToAsyncStorage();
61+
}
62+
63+
saveToAsyncStorage(callback) {
64+
AsyncStorage.setItem(this.props.storageKey, encodeState(this.state), callback);
65+
}
66+
67+
}
68+
69+
export default NativeHistory;

0 commit comments

Comments
 (0)