aboutsummaryrefslogtreecommitdiff
import './SignUp.css'
import { useEffect } from 'react';
import { useForm } from 'react-hook-form'
import { zodResolver } from "@hookform/resolvers/zod"
import { useLocation, Navigate, useNavigate } from 'react-router-dom';
import { Form1Data, Form2Data, Form3Data, form3Schema } from './signUpSchema'

import { useQuery, QueryClient, QueryClientProvider } from 'react-query'

export const SignUpForm3 = () => {
  const queryClient = new QueryClient()

  return (
    <QueryClientProvider client={queryClient}>
      <SignUpForm3Main />
    </QueryClientProvider>
  )
}


export const SignUpForm3Main = () => {
  const { register, watch, setValue, handleSubmit, formState: { errors } } = useForm<Form3Data>({
    resolver: zodResolver(form3Schema),

  });
  const location = useLocation();
  const formData = location.state as { form1: Form1Data, form2: Form2Data } | null;
  const navigate = useNavigate();
  const watchHasGithubRepo = watch("hasGithubRepo", false)
  const githubUsername = watch("githubUsername", '')

  const repoQueryEnabled = watchHasGithubRepo && githubUsername.length > 0;

  const { data: reposData, isLoading: reposIsLoading, isError: reposIsError, error: reposError } = useQuery({
    queryKey: ['githubRepos', githubUsername],
    queryFn: async () => {
      const res = await fetch(`https://api.github.com/users/${githubUsername}/repos?sort=updated&direction=desc&per_page=100`)
      if (res.ok) { return res.json(); }
      throw new Error(res.statusText)
    },
    enabled: repoQueryEnabled,
  })

  const repoNames: [string] = (repoQueryEnabled && !reposIsLoading && !reposIsError) ?
    (reposData.map((json: any) => (json['name']))) :
    []

  useEffect(() => {
    setValue('githubUsername', '')
    setValue('repoName', '')
  }, [watchHasGithubRepo])

  // form1, form2 のデータがない場合は form1 にリダイレクトする
  if (formData === null) {
    return <Navigate replace to="/sign-up/form1" />
  }

  const { form1, form2 } = formData;

  const onsubmit = (form3: Form3Data) => {
    const state = { form1, form2, form3 }
    navigate('/sign-up/confirm', { state })
  }
  const onerror = (err: any) => console.log(err);

  return (
    <>
      <h1>会員登録 フェーズ 3</h1>
      <form className="SignUpForm" onSubmit={handleSubmit(onsubmit, onerror)}>
        <div>
          <label htmlFor="hasGithubRepo">GitHubのリポジトリある?: </label>
          <input id="hasGithubRepo" type="checkbox" {...register('hasGithubRepo')}></input>
          <div className="error">{errors.hasGithubRepo?.message}</div>
        </div>
        {
          (watchHasGithubRepo &&
            <div>
              <label htmlFor="githubUsername">github username: </label>
              <input id="githubUsername" type="text" {...register('githubUsername')}></input>
            </div>
          )
        }
        {
          repoQueryEnabled && (
            (
              reposIsLoading ? 'Loading...' :
                reposIsError ? `Error: ${reposError}` :
                  <div>
                    <label htmlFor="repoName">お気に入りのリポジトリを選んでください:</label>
                    <select id="repoName" {...register('repoName')}>
                      {repoNames.map((repoName) => (
                        <option key={repoName} value={repoName}>{repoName}</option>
                      ))}
                    </select>
                  </div>
            )
          )
        }
        <div>
          <button type="submit">確認画面へ</button>
        </div>
      </form >
    </>
  );
}