1. screens/login.js
import React, { useRef } from 'react'
import { Text, View } from 'react-native'
import { TouchableOpacity } from 'react-native-gesture-handler'
import AuthLayout from '../components/auth/AuthLayout'
import { TextInput } from '../components/auth/AuthShared'
import { Controller, useForm } from 'react-hook-form'
import AuthButton from '../components/auth/AuthButton'
import { gql, useMutation } from '@apollo/client'
import { isLoggedInVar, logUserIn } from '../apollo'
import AsyncStorage from '@react-native-async-storage/async-storage'
const LOGIN_MUTAITION = gql` ///1. loggin mutation 만들어줌
///return 값으로 ok, token, error받음.
mutation login($username: String!, $password: String!) {
login(username: $username, password: $password) {
ok
token
error
}
}
`
export default function Login({ route: { params } }) {
///4. createAccount page에서 navigation으로 보내온 값들을
const { ///route:{params}로 받아줌.
register, ///그리고 form의 default값으로 넣어줌.
setValue,
handleSubmit,
control,
watch,
reset,
formState: { errors },
} = useForm({
defaultValues: {
username: params?.username,
password: params?.password,
},
})
const passwordRef = useRef()
const onCompleted = async (data) => { ///3.login mutation성공시
const { ///token을 logUserIn에 넣어줌.
login: { ok, token }, ///token부분은 다음장에서 다룸.
} = data
if (ok) {
await logUserIn(token)
}
}
const [loginMutation, { loading }] = useMutation(LOGIN_MUTAITION, {
onCompleted, ///2. useMutation만들어줌!!!!
///mutaiton 성공시 실행될 onCompleted함수 만듬.
})
const onSubmit = (data) => {
if (!loading) {
loginMutation({
variables: {
...data,
},
})
}
}
const onNext = (nextOne) => {
nextOne?.current?.focus()
}
const onDone = () => {
alert('done!')
}
return (
<AuthLayout>
<Controller
control={control}
name="username"
rules={{ requirred: true }}
render={({ field: { onChange, onBlur, value } }) => (
<TextInput
placeholder="Username"
placeholderTextColor="gray"
returnKeyType="next"
onSubmitEditing={() => onNext(passwordRef)}
onChangeText={(value) => onChange(value)}
value={value}
onBlur={onBlur}
/>
)}
/>
<Controller
control={control}
name="password"
rules={{ requirred: true }}
render={({ field: { onChange, onBlur, value } }) => (
<TextInput
ref={passwordRef}
placeholder="Password"
placeholderTextColor="gray"
returnKeyType="next"
onSubmitEditing={onDone}
onChangeText={(value) => onChange(value)}
value={value}
onBlur={onBlur}
secureTextEntry
/>
)}
/>
<AuthButton
text="Login"
disabled={!watch('username') || !watch('password')}
onPress={handleSubmit(onSubmit)}
/>
</AuthLayout>
)
}