TIL | firebase, React-hook-form

unihit·2021년 3월 7일
0

TIL

목록 보기
18/25
post-thumbnail

firebase와 react-hook-form 사용시 필요한점

register 폼에 errors가 랜더링되어 출력되지 않길래 이상하게 생각했더니...

Firebase의 프로젝트 페이지로 이동해서 빌드 항목의 Authentication을 시작하기를 눌러줘야 제대로 값이 전달 되는 거였다.

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/03905728-919d-45f9-adfa-3d6109bf8b5c/_2021-03-02__12.07.47.png

import React, { useState, useRef } from "react";
import { Link } from "react-router-dom";
import { useForm } from "react-hook-form";
import firebase from "../../firebase";

export default function RegisterPage() {
  const { register, watch, errors, handleSubmit } = useForm();
  const [errorFromSubmit, setErrorFromSubmit] = useState("");
  const password = useRef();
  password.current = watch("password");

  const onSubmit = async (data) => {
    try {
      let createdUser = await firebase
        .auth()
        .createUserWithEmailAndPassword(data.email, data.password);
    } catch (error) {
      setErrorFromSubmit(error.message);
    }
  };

  return (
    <div className="auth-wrapper">
      <div style={{ textAlign: "center" }}>
        <h3>Register</h3>
      </div>
      <form onSubmit={handleSubmit(onSubmit)}>
        <label>Email</label>
        <input
          name="email"
          type="email"
          ref={register({ required: true, pattern: /^\S+@\S+$/i })}
        />
        {errors.email && <p>This email field is required</p>}

        <label>Name</label>
        <input name="name" ref={register({ required: true, maxLengt: 10 })} />
        {errors.name && errors.name.type === "required" && (
          <p>This email field is required</p>
        )}
        {errors.name && errors.name.type === "maxLength" && (
          <p>Your input exceed maximum length</p>
        )}
        <label>Password</label>
        <input
          name="password"
          type="password"
          ref={register({ required: true, minLength: 6 })}
        />
        {errors.password && errors.password.type === "required" && (
          <p>This password field is required</p>
        )}
        {errors.password && errors.password.type === "minLength" && (
          <p>Password must have at least 6 characters</p>
        )}
        <label>Password Confirm</label>
        <input
          name="password_confirm"
          type="password"
          ref={register({
            required: true,
            validate: (value) => value === password.current,
          })}
        />
        {errors.password_confirm &&
          errors.password_confirm.type === "required" && (
            <p>This password confirm field is required</p>
          )}
        {errors.password_confirm &&
          errors.password_confirm.type === "validate" && (
            <p>The password do not match</p>
          )}
        {errorFromSubmit && <p>{errorFromSubmit}</p>}
        <input type="submit" />
        <Link style={{ color: "gray", textDecoration: "none" }} to="login">
          이미 아이디가 있다면...
        </Link>
      </form>
    </div>
  );
}

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/0520306b-d576-4605-9ec6-08a012a279c2/_2021-03-02__12.11.13.png

이제 설정한대로 제대로 랜더링 되는 것을 볼 수 있다.

제대로 로그인을 하기 위해서 이메일을 입력하고 제대로 가입하려고 하니까 아래와 같은 에러가 발생한다.

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/cb0980ab-f931-45e6-9324-01b525c1bc79/_2021-03-02__12.24.10.png

이를 해결하기 위해서는 Firebase의 Authentication으로 이동해서 Sign-in method 탭으로 간 뒤에 내가 사용할 항목에 대한 설정을 해줘야 한다.

나는 이메일로 해줄거라 이메일/비밀번호 항목을 설정해준다.

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/bbc44a2c-345c-4cff-a82c-0c322a4fe44f/_2021-03-02__12.29.04.png

Firebase에서 데이터베이스 사용하기

채팅 프로그램에서

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/e088c23b-86c7-4481-8731-7cb5b50623c3/_2021-03-02__12.50.57.png

데이터베이스 만들기를 클릭

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/ab570f36-0b29-432c-9b10-1e0d729452cb/_2021-03-02__12.52.43.png

데이터베이스 옵션에서 미국을 선택해주고 보안 규칙은 연습용이기 때문에 테스트 모드에서 시작으로 사용 설정을 해준다.

0개의 댓글