App에 감싸줘서 전역으로 Auth를 접근할 수 있다.
import React from 'react';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { AuthContextProvider } from './src/api/Auth';
import Navigator from "./src/navigation";
const App = () => {
return (
<SafeAreaProvider>
<AuthContextProvider>
<Navigator />
</AuthContextProvider>
</SafeAreaProvider>
);
}
export default App;
Navigation에서 auth의 userToken 바탕으로 화면을 랜더링할 수 있다.
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { useAuthContext } from '../api/Auth';
import HomeTab from './HomeTab';
import Login from '../components/Login';
const Stack = createStackNavigator();
export default () => {
**const { auth: { isLoading, userToken, isSignout } } = useAuthContext();**
if (isLoading)
return <View><Text>Loading...</Text></View>;
return (
<NavigationContainer>
<Stack.Navigator headerMode="float" screenOptions={{ headerShown: false }}>
{
userToken ?
<Stack.Screen name="HomeTab" component={HomeTab} />
:
<Stack.Screen name="Login" component={Login} />
}
</Stack.Navigator>
</NavigationContainer >
)
}
앞서 useReducer로 만든 auth를 조회할 수 있다.
앞서 useAuth (useMemo) 로 작성한 함수를 활용할 수 있다
import React, { useState } from 'react'
import styled from 'styled-components/native';
import { Input } from 'react-native-elements'
import Icon from 'react-native-vector-icons/EvilIcons';
import { useAuthContext } from '../../api/Auth';
const LoginForm = () => {
const [id, setId] = useState("")
const [pw, setPw] = useState("")
**const { useAuth: { signIn } } = useAuthContext();**
return (
<Container>
<Input
onChangeText={(text: string) => setId(text)}
inputStyle={{textAlign: "center"}}
/>
<Input
onChangeText={(text: string) => setPw(text)}
secureTextEntry={true}
inputStyle={{textAlign: "center"}}
/>
<Btns>
<Icon name="sc-telegram" color="#517fa4" size={70} onPress={() => signIn({id, pw})} />
<Icon name="sc-github" color="#517fa4" size={70} onPress={onClick} />
</Btns>
</Container>
)
}
export default LoginForm;
const Container = styled.View`
flex: 1;
justify-content: center;
align-items: center;
`
const Btns = styled.View`
flex-direction: row;
`