Skip to content

Instantly share code, notes, and snippets.

@rob-mcgrail
Last active September 6, 2017 02:33
Show Gist options
  • Save rob-mcgrail/7d368e61675296bc053199a67d7829ae to your computer and use it in GitHub Desktop.
Save rob-mcgrail/7d368e61675296bc053199a67d7829ae to your computer and use it in GitHub Desktop.
Wrap children in a loader that fetches authentication data from the phone's storage and bootup.
// Requests
import { loadAuth, saveAuth } from 'src/requests/storage/auth';
// Types
export const types = {
AUTH_REHYDRATE: 'app/auth/rehydrate'
};
/* Action creators */
export function rehydrate() {
return dispatch =>
loadAuth()
.then((value) => {
dispatch({
type: types.AUTH_REHYDRATE,
payload: value
});
})
.catch((e) => {
console.log(e);
});
}
/* Reducer defaults */
export const defaultState = {
authenticated: false
};
/* Define reducer */
export default function (state = defaultState, action) {
switch (action.type) {
case types.AUTH_REHYDRATE:
return { ...state, authenticated: action.payload };
default:
return state;
}
}
import { AsyncStorage } from 'react-native';
import config from 'src/config';
export async function loadAuth() {
const value = await AsyncStorage.getItem(
`${config.keyPrefix}auth`
);
return JSON.stringify(value);
}
export async function saveAuth(value) {
AsyncStorage.setItem(
`${config.keyPrefix}auth`,
JSON.stringify(value)
);
}
import React, { Component } from 'react';
import PropTypes from 'prop-types';
const Loading = (Wrapped, action) => class extends Component {
static propTypes = {
action: PropTypes.func
}
static defaultProps = {
action: false
}
constructor(props) {
super(props);
this.state = {
loaded: false,
action: action || this.props.action
};
}
componentDidMount() {
this.state.action().then(() => this.setState({ loaded: true }));
}
render() {
if (this.state.loaded) {
return <Wrapped {...this.props} />;
}
return null; // Add an optional loader here
}
};
export default Loading;
import { connect } from 'react-redux';
import { Container } from 'native-base';
import Loading from 'src/components/utility/Loading';
import { rehydrate } from 'src/redux/modules/auth';
const StoredSession = connect(
null, { action: rehydrate }
)(Loading(Container));
export default StoredSession;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment