useMutation in native(createAccount)

김종민·2022년 5월 19일
1

insta-native

목록 보기
7/36

들어가기
native에서 useMutaion을 사용하는 방법임
web과 다른점이 없다.
별표 부분만 확인해면서 check해 볼것

screens/CreateAccount.js

import { gql, useMutation } from '@apollo/client'
import React, { useRef } from 'react'
import { Controller, useForm } from 'react-hook-form'
import AuthButton from '../components/auth/AuthButton'
import AuthLayout from '../components/auth/AuthLayout'
import { TextInput } from '../components/auth/AuthShared'
import styled from 'styled-components/native'

const CREATE_ACCOUNT_MUTATION = gql` ////1. createAccount mutation을 만든다.
                                     /// ok, error return받음.
  mutation createAccount(
    $username: String!
    $email: String!
    $password: String!
  ) {
    createAccount(username: $username, email: $email, password: $password) {
      ok
      error
    }
  }
`
const Text = styled.Text`
  color: white;
  width: 100%;
  background-color: red;
`

export default function CreateAccount({ navigation }) {
  const {
    register,
    setValue,
    handleSubmit,
    control,
    reset,
    getValues,
    formState: { errors },
  } = useForm({
    defaultValues: {
      username: '',
      email: '',
      password: '',
    },
  
  })
  const onCompleted = (data) => {  ///3.onCompleted 함수만들어줌.
                                   ///return으로 ok 를 받았을때,
                                   ///Login screen으로 이동하고
                                   ////props로 username, password보내줌.
                                   ///getValues()로 입력된 값얻음,
                                   ///page이동시 state를 보내느것은 매우 중요!
                                   ///login page에서 route로 받음
    const {
      createAccount: { ok },
    } = data
    const { username, password } = getValues()
    if (ok) {
      navigation.navigate('Login', {
        username,
        password,
      })
    }
  }

  const [createAccountMutation, { loading }] = useMutation(
    CREATE_ACCOUNT_MUTATION,  ///2.useMutation을 만들어줌,onCompleted 함수 
                              ///만들어서 return ok받을시, 다음 로직이어줌.
    { onCompleted }
  )

  const onSubmit = (data) => {
    if (!loading) {
      createAccountMutation({
        variables: {
          ...data,
        },
      })
    }
  }
  const emailRef = useRef()
  const passwordRef = useRef()

  const onNext = (nextOne) => {
    nextOne?.current?.focus()
  }
  const onDone = () => {
    alert('done!')
  }
  console.log(errors)
  return (
    <AuthLayout>
      <Controller
        control={control}
        name="username"
        rules={{
          required: true,
        }}
        render={({ field: { onChange, onBlur, value } }) => (
          <TextInput
            placeholder="Username"
            placeholderTextColor="gray"
            returnKeyType="next"
            onSubmitEditing={() => onNext(emailRef)}
            onChangeText={(value) => onChange(value)}
            value={value}
            onBlur={onBlur}
          />
        )}
      />
      {errors?.username?.types === 'required' && (
        <Text>username is required</Text>
      )}
      <Controller
        control={control}
        name="email"
        rules={{ required: true }}
        render={({ field: { onChange, onBlur, value } }) => (
          <TextInput
            ref={emailRef}
            placeholder="Email"
            placeholderTextColor="gray"
            returnKeyType="next"
            keyboardType="email-address"
            onSubmitEditing={() => onNext(passwordRef)}
            onChangeText={(value) => onChange(value)}
            value={value}
            onBlur={onBlur}
          />
        )}
      />
      {errors?.email && (
        <Text>
          This is required.
        </Text>
      )}
      <Controller
        control={control}
        rules={{ required: true}}
        render={({ field: { onChange, onBlur, value } }) => (
          <TextInput
          ref={passwordRef}
          placeholder="Password"
          placeholderTextColor="gray"
          returnKeyType="done"
          onSubmitEditing={onDone}
          onChangeText={(value) => onChange(value)}
          value={value}
          onBlur={onBlur}
          secureTextEntry
          />
          )}
          name="password"
      />
      {errors?.password && (
        <Text>
          This is required.
        </Text>
      )}
      <AuthButton
        text="Create Account"
        disabled={false}
        onPress={handleSubmit(onSubmit)}
      />
    </AuthLayout>
  )
}
profile
코딩하는초딩쌤

0개의 댓글