Skip to content

Instantly share code, notes, and snippets.

@keith-kurak
Last active December 29, 2021 18:03
Show Gist options
  • Select an option

  • Save keith-kurak/bef74afae88c38bdb4bfe9c530ac4e09 to your computer and use it in GitHub Desktop.

Select an option

Save keith-kurak/bef74afae88c38bdb4bfe9c530ac4e09 to your computer and use it in GitHub Desktop.
04: Hello, Authentication!
Follow the steps below to add login capabilities!
// add user model variable
user: types.frozen() // could be anything
// also set isLoggedIn to default to false so MST can check
// add login/ logout actions
const login = flow(function* login({ username, password }) {
const auth = getAuth();
try {
const user = yield signInWithEmailAndPassword(auth, username, password);
console.log(user);
} catch (error) {
console.log(error);
}
});
const logout = flow(function* logout() {
const auth = getAuth();
try {
yield signOut(auth);
} catch (error) {
// eh?
}
});
// add afterCreate action to track auth status
const afterCreate = () => {
const auth = getAuth();
onAuthStateChanged(auth, (user) => {
if (user) {
self.setIsLoggedIn(true, user);
} else {
self.setIsLoggedIn(false, null);
}
});
};
// add text inputs
<TextInput
onChangeText={(text) => setUsername(text)}
value={username}
placeholder="Email"
style={textInputStyle}
/>
<TextInput
onChangeText={(text) => setPassword(text)}
value={password}
placeholder="Password"
secureTextEntry
style={textInputStyle}
/>
// pass state to rootStore.login()
<Button
onPress={() => rootStore.login({ username, password })}
title="Login"
/>
// import LogBox
// hide the error! Just need to supply some of the starting string
// this is kind of the unfortunate reality of using deps that use core functionality of the ever-changing RN ecosystem
LogBox.ignoreLogs(['AsyncStorage has been extracted']);
// BONUS: come back and add the following to the model:
loginError: types.frozen(), // just store an error here
isLoading: types.optional(types.boolean, false), // set to true while login is happening
// then modify login() action to set these. Use try/ catch to set the error
// Add an error under the password text input
{rootStore.loginError && (
<Text style={{ color: "red", marginVertical: 10 }}>
Login failed! Check that your email and password are correct.
</Text>
)}
// you can also wrap the contents of this screen in LoadingWrapper to show a spinner
<LoadingWrapper isLoading={rootStore.isLoading}>
{...}
</LoadingWrapper>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment