Skip to content

Instantly share code, notes, and snippets.

@oriharel
Created August 24, 2019 08:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oriharel/d9106b7e1413b350d2e205ccb3200d79 to your computer and use it in GitHub Desktop.
Save oriharel/d9106b7e1413b350d2e205ccb3200d79 to your computer and use it in GitHub Desktop.
AWS Amplify with MobX in React Native
import { createAppContainer, createSwitchNavigator } from 'react-navigation';
import UserNotAuthorized from './src/screens/UserNotAuthorized/UserNotAuthorized';
import DisclaimerScreen from './src/screens/DisclaimerScreen/DisclaimerScreen';
import React from 'react';
import { withAuthenticator } from 'aws-amplify-react-native';
import { Auth } from 'aws-amplify';
import { action, observable, reaction } from 'mobx';
import { Props, State } from './src/boot/setup';
import { Provider } from 'mobx-react/native';
const AppNavigator = createSwitchNavigator({
Screen1: Screen1,
Screen2: Screen2,
Screen3: Screen3,
Screen4: Screen4
});
//InnerApp.js
export default props => {
const AppComponent = withAuthenticator(createAppContainer(AppNavigator));
return <AppComponent {...props} />;
};
//App.js
class App extends React.Component<Props, State> {
constructor(props) {
super(props);
this.reloadDisposer = reaction(
() => stores.userStore.rerender,
rerender => {
if (rerender) {
this.rerender();
stores.userStore.rerender = false;
}
}
);
}
componentWillUnmount(): void {
this.reloadDisposer();
}
rerender = () => this.forceUpdate();
render() {
return (
<Provider {...stores}>
<InnerApp />
</Provider>
);
}
}
//MobX store
export class UserStore {
@observable rerender: boolean = false;
@action
reloadApp() {
this.rerender = true;
}
logout() {
Auth.signOut().then(() => this.reloadApp());
}
}
@oriharel
Copy link
Author

This a non-working example of how I used MobX in React Native.
In this example, I needed to implement a sign out flow. Since I'm rendering the entire app embedded inside withAuthentication HOC, the only way to navigate back to aws-amplify Sign In page is to reload the app.
So, signing out sets an @observable variable to true (rerender, owned by UserStore).
Inside the root component (App.js), I've armed a MobX reaction to listen to changes on that parameter, forcing the app to render and setting the variable back. This flow is inspired by @dabit3 answer to a github issue.

Feel free to comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment