티스토리 뷰

필요한 패키지를 설치한다.

npm i typescript @type/node @type/react @type/react-dom @type/react-router-dom
// jest도 사용한다면 추가한다.
npm i typescript @type/node @type/react @type/react-dom @type/react-router-dom @type/jest

 

파일 확장자를 변경한다.

.js => .ts
.jsx => .tsx

 

tsx로 변경한 파일부터 타입 스크립트를 얹어준다.

interface를 선언하여 props에 type을 정해주거나 generic을 사용해가며 에러들을 해결해준다.

 

 

ref.current 에러 해결하기

jsx를 tsx로 파일 속성을 변경하면 e와 ref.current에 빨간 줄이 뜬다.

...

export default function CreateWord() {
  const days = useFetch("http://localhost:3001/days");
  const history = useHistory();
  const [isLoading, setIsLoading] = useState(false);

  function onSubmit(e) {
    e.preventDefault();

    if (!isLoading) {
      setIsLoading(true);

      const day = dayRef.current.value;
      const eng = engRef.current.value;
      const kor = korRef.current.value;

      fetch(`http://localhost:3001/words/`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          day: dayRef.current.value,
          eng: engRef.current.value,
          kor: korRef.current.value,
          isDone: false,
        }),
      }).then(res => {
        if (res.ok) {
          alert("생성이 완료 되었습니다");
          history.push(`/day/${dayRef.current.value}`);
          setIsLoading(false);
        }
      });
    }
  }

  const engRef = useRef(null);
  const korRef = useRef(null);
  const dayRef = useRef(null);

 

 

1. cons 000Ref 부분에서 <HTMLElement>들을 제네릭으로 넣어준다. (html element와 똑같이 들어오기 때문에)

2. isLoading이 끝났을 때 사용하는 ref 값이 null일수도 있기 때문에 에러가 뜬다. 그래서 조건부 렌더링을 같이 걸어준다. 이미 검증되어서 값이 들어오기 때문에 안전하게 사용할 수 있다.

ref.current를 사용할 때는 렌더링이 끝난 뒤에도 null일 수 있기 때문에 값을 체크해주는 것이 좋다. (해당 요소가 조건에 따라 보일 수도 있고 안보일 수도 있기 때문에..)

export default function CreateWord() {
  const days: IDay[] = useFetch("http://localhost:3001/days");
  const history = useHistory();
  const [isLoading, setIsLoading] = useState(false);

  function onSubmit(e: React.FormEvent) {
    e.preventDefault();

    if (!isLoading && dayRef.current && engRef.current && korRef.current) {
      setIsLoading(true);

      const day = dayRef.current.value;
      const eng = engRef.current.value;
      const kor = korRef.current.value;

      fetch(`http://localhost:3001/words/`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          day,
          eng,
          kor,
          isDone: false,
        }),
      }).then(res => {
        if (res.ok) {
          alert("생성이 완료 되었습니다");
          history.push(`/day/${day}`);
          setIsLoading(false);
        }
      });
    }
  }

  const engRef = useRef<HTMLInputElement>(null);
  const korRef = useRef<HTMLInputElement>(null);
  const dayRef = useRef<HTMLSelectElement>(null);

 

참고 : 코딩앙마 유튜브

728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
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
글 보관함