All files / src/components/transfer_item TransferSearchItemForm.tsx

0% Statements 0/43
0% Branches 0/1
0% Functions 0/1
0% Lines 0/43

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62                                                                                                                           
import { SubmitHandler, useForm } from 'react-hook-form';
import { searchItemSchema, SearchItemSchemaType } from '../../validations/searchItem';
import { zodResolver } from '@hookform/resolvers/zod';
import { Dispatch, FC, SetStateAction, useState } from 'react';
import { ErrorMessage } from '@hookform/error-message';
import { SearchItemsResponse } from '../../models/searchItemResponse';
import { ErrorResponse } from '../../models/errorResponse';
import { Pending } from '../../models/pending';
import { useFetchSearchItemWithoutUseEffect } from '../../hooks/useFetchSearchItemWithoutUseEffect';
import { OkResponse } from '../../models/okResponse';
import TransferSearchItemResult from './TransferSearchItemResult';
 
type Props = {
  id: string;
  setTransferResult: Dispatch<SetStateAction<OkResponse | ErrorResponse | Pending | null>>;
};
 
const TransferSearchItemForm: FC<Props> = (props) => {
  // get keywords
  const [keywords, setKeywords] = useState<string>('');
  // get search result
  const [searchResult, setSearchResult] = useState<SearchItemsResponse | ErrorResponse | Pending | null>(null);
  // react hook form
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<SearchItemSchemaType>({
    resolver: zodResolver(searchItemSchema),
  });
  // update url
  const onSubmit: SubmitHandler<SearchItemSchemaType> = async (formData) => {
    setKeywords(formData.keywords);
    const data: SearchItemsResponse | ErrorResponse | Pending = await useFetchSearchItemWithoutUseEffect(
      formData.keywords
    );
    setSearchResult(data);
  };
  return (
    <>
      {/* form */}
      <form onSubmit={handleSubmit(onSubmit)}>
        <label htmlFor="keywords">Search: </label>
        <input id="keywords" type="text" {...register('keywords')} placeholder="Search" />
        <br />
        <ErrorMessage errors={errors} name="keywords" message={errors.keywords?.message} />
        <br />
        <input type="submit" value="検索" />
      </form>
      {/* result */}
      <TransferSearchItemResult
        keywords={keywords}
        result={searchResult}
        id={props.id}
        setTransferResult={props.setTransferResult}
      />
    </>
  );
};
 
export default TransferSearchItemForm;