개인프로젝트: VarGen(5.3)-입력데이터 관련 버튼 만들기

윤뿔소·2023년 3월 27일
0

개인프로젝트: VarGen

목록 보기
11/15

여기서 기능 기획을 했던 것 처럼
Create {countVariable} {subject} related variable names with {namingConvention}
이런 식으로 변수화 시켜서 prompt변수에 할당할 것이다! 자연스레 저 변수들을 버튼으로 만들어 값을 넣을 것이다!

간편 메뉴 구현

이제 버튼 메뉴 및 주제별로 값을 받는 걸 구현하려고 한다.

input 없애기

저 변수들을 상태로 만들어야겠지? 그러니 3개의 상태를 만들고 inputValue를 없애보자!

import { useState } from "react";
import { QueryClient, QueryClientProvider } from "react-query";
import { ReactQueryDevtools } from "react-query/devtools";
import { ChatResponse } from "./ChatResponse";

const queryClient = new QueryClient();

export default function PromptInput() {
  // const [inputValue, setInputValue] = useState("");
  const [promptValue, setPromptValue] = useState<string>("");

  const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    queryClient.invalidateQueries("chatResponse");
    setPromptValue(
      `Create ${countVariable} ${subject} related variable names with ${namingConvention}`
    );
    //   if (inputValue !== "") {
    //     setPromptValue(inputValue);
    //   }
  };

  return (
    <QueryClientProvider client={queryClient}>
      <form onSubmit={handleSubmit}>
        {/* <input type="text" value={inputValue} onChange={(e) => setInputValue(e.target.value)} /> */}

        <button type="submit">Submit</button>
      </form>
      {/* <ChatResponse prompt={`Create 10 게시판 related variable names with camelCase`} /> */}
      {promptValue && <ChatResponse prompt={promptValue} />}
      <ReactQueryDevtools />
    </QueryClientProvider>
  );
}

input을 없애고, Create ${countVariable} ${subject} related variable names with ${namingConvention}를 넣었다.

상태 구현

3개 상태를 제작하겠다! countVariable, subject, namingConvention를 state로 만들어보자!

// import문 동일

type CountVariable = 5 | 10 | 20;
type NamingConvention = "camelCase" | "PascalCase" | "snake_case";

export default function PromptInput() {
  // const [inputValue, setInputValue] = useState("");
  const [countVariable, setCountVariable] = useState<CountVariable>(5);
  const [subject, setSubject] = useState<string>("");
  const [namingConvention, setNamingConvention] = useState<NamingConvention>("");
  const [promptValue, setPromptValue] = useState<string>("");
  
// 동일

이렇게 말이다! type 선언자로 들어갈 값을 먼저 설정했고, 각각 맞는 상태를 만들었다.

setState 관련 함수 구현

handleChange 관련 함수를 만들어보았다.

// 동일
  const handleCountChange = (e: ChangeEvent<HTMLSelectElement>) => {
    setCountVariable(parseInt(e.target.value) as CountVariable);
  };

  const handleSubjectChange = (e: ChangeEvent<HTMLInputElement>) => {
    setSubject(e.target.value);
  };

  const handleNamingConventionChange = (e: ChangeEvent<HTMLSelectElement>) => {
    setNamingConvention(e.target.value as NamingConvention);
  };
// 동일

이거 하는데 좀 오래 걸렸다. 망할 타입 ㅋㅋㅋㅋ 특히 setCountVariable부분 할 때인데 그냥 네이밍컨벤션과 똑같이 했는데 오류가 생겼다.

사소한 오류

'string' 형식을 'CountVariable' 형식으로 변환한 작업은 실수일 수 있습니다. 두 형식이 서로 충분히 겹치지 않기 때문입니다. 의도적으로 변환한 경우에는 먼저 'unknown'으로 식을 변환합니다.

처음에 이걸 보고 unknown도 같이 단언해야하나? 이게 맞나? 싶었다. 그렇게 하니깐 되긴 됐기도 했고 말이다. 근데 아무리 봐도 as unknown as CountVariable 이 모양이 아닌 거 같았다. 구글링한 결과 그냥 countVariable 변수 자체의 타입이 균일하게 들어오지 않을 수도 있어서 오류가 뜨는 것이다. 실제로 string값이 들어오기도 했고, 그래서 parseInt를 써서 타입을 고정시켰다.

DOM 구현

return (
    <QueryClientProvider client={queryClient}>
      <form onSubmit={handleSubmit}>
        {/* <input type="text" value={inputValue} onChange={(e) => setInputValue(e.target.value)} /> */}
        <label>
          Number of Variables:
          <select value={countVariable} onChange={handleCountChange}>
            <option value="5">5</option>
            <option value="10">10</option>
            <option value="20">20</option>
          </select>
        </label>
        <br />
        <label>
          Subject:
          <input type="text" value={subject} onChange={handleSubjectChange} />
        </label>
        <br />
        <label>
          Naming Convention:
          <select value={namingConvention} onChange={handleNamingConventionChange}>
            <option value="camelCase">camelCase</option>
            <option value="PascalCase">PascalCase</option>
            <option value="snake_case">snake_case</option>
          </select>
        </label>
        <br />
        <button type="submit">Submit</button>
      </form>

      {/* <ChatResponse prompt={`Create 10 게시판 related variable names with camelCase`} /> */}
      {promptValue && <ChatResponse prompt={promptValue} />}
      <ReactQueryDevtools />
    </QueryClientProvider>
  );
}

일단 임시로 되게 조악하게 했다. 드롭다운 메뉴를 구현하고 싶어서 selectoption 태그를 작성했고, subjectinput 태그로 직접 입력하게 했다.

여기서 아쉬운 점은 간편하게 클릭으로만 끝내고 싶은데 subject 자체가 input으로만 하는 거 같아 아쉬웠다. 나중에 디자인 완성되고 나면 모달창으로 연 다음 버튼 식으로도 구현 해볼 것이다.

결과

디자인 없어서 이상하긴 하지만 쨌든 저기서 값을 넣고 Submit 버튼을 누르면?

이렇게 되면 끝이다! 은근 오래 걸렸다! 이제 저 메뉴들을 디자인 하고, 결과값도 예쁘게 나오게 디자인해보겠다.. 디자인이 오래 걸리고 귀찮더라 나는 ;;

profile
코뿔소처럼 저돌적으로

6개의 댓글

comment-user-thumbnail
2023년 3월 28일

오 이제 거의 완성하셨네요 수고하셨어요!

답글 달기
comment-user-thumbnail
2023년 3월 29일

너무 멋집니다 !! 고생하셨어욥 !!

답글 달기
comment-user-thumbnail
2023년 4월 2일

오호 오류 해결 방법에서 또 하나 배워갑니다ㅎㅎ

답글 달기
comment-user-thumbnail
2023년 4월 2일

끝이 보이는군요 !

답글 달기
comment-user-thumbnail
2023년 4월 2일

오호 과정을 보니 더 흥미롭네용

답글 달기
comment-user-thumbnail
2023년 4월 2일

과정 공유해주시는 거 넘나 좋아요! 따라만들어야지

답글 달기