Created
July 22, 2020 17:00
-
-
Save Reston/f8ccf27c0888f941a25dda619ecd94d9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react'; | |
import AsyncStorage from '@react-native-community/async-storage'; | |
export default function App({ navigation }) { | |
const [state, dispatch] = React.useReducer( | |
(prevState, action) => { | |
switch (action.type) { | |
case 'RESTORE_TOKEN': | |
return { | |
...prevState, | |
userToken: action.token, | |
isLoading: false, | |
}; | |
case 'SIGN_IN': | |
return { | |
...prevState, | |
isSignout: false, | |
userToken: action.token, | |
}; | |
case 'SIGN_OUT': | |
return { | |
...prevState, | |
isSignout: true, | |
userToken: null, | |
}; | |
} | |
}, | |
{ | |
isLoading: true, | |
isSignout: false, | |
userToken: null, | |
} | |
); | |
React.useEffect(() => { | |
// Fetch the token from storage then navigate to our appropriate place | |
const bootstrapAsync = async () => { | |
let userToken; | |
try { | |
userToken = await AsyncStorage.getItem('userToken'); | |
} catch (e) { | |
// Restoring token failed | |
} | |
// After restoring token, we may need to validate it in production apps | |
// This will switch to the App screen or Auth screen and this loading | |
// screen will be unmounted and thrown away. | |
dispatch({ type: 'RESTORE_TOKEN', token: userToken }); | |
}; | |
bootstrapAsync(); | |
}, []); | |
const authContext = React.useMemo( | |
() => ({ | |
signIn: async data => { | |
// In a production app, we need to send some data (usually username, password) to server and get a token | |
// We will also need to handle errors if sign in failed | |
// After getting token, we need to persist the token using `AsyncStorage` | |
// In the example, we'll use a dummy token | |
dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' }); | |
}, | |
signOut: () => dispatch({ type: 'SIGN_OUT' }), | |
signUp: async data => { | |
// In a production app, we need to send user data to server and get a token | |
// We will also need to handle errors if sign up failed | |
// After getting token, we need to persist the token using `AsyncStorage` | |
// In the example, we'll use a dummy token | |
dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' }); | |
}, | |
}), | |
[] | |
); | |
return ( | |
<AuthContext.Provider value={authContext}> | |
<Stack.Navigator> | |
{state.userToken == null ? ( | |
<Stack.Screen name="SignIn" component={SignInScreen} /> | |
) : ( | |
<Stack.Screen name="Home" component={HomeScreen} /> | |
)} | |
</Stack.Navigator> | |
</AuthContext.Provider> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment