💭 개요

질문 블럭에서 질문을 입력하고 Enter 를 누르면 질문이 추가가 돼요.

❤️‍🩹 문제 상황

해당 기능을 구현하던 중 다음과 같은 이슈를 발견했어요.

한글을 입력하고 Enter 를 누르면 이벤트가 2번이나 발생해요.

const onKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
  if (e.key !== 'Enter') return;

  e.preventDefault();

  const target = e.target as HTMLInputElement;
  const { value: question } = target;

  if (!question) return;

  createQuestion(question);
  target.value = '';
};

화면 기록 2022-11-29 오전 10.57.14.mov

알고보니 한글은 영어와 다르게 자음과 모음이 합쳐져야 한 글자가 되기 때문에 이 문자가 조합중인지 아닌지 파악하기 위해서 이벤트가 2번 발생하게 돼요.

🔧 해결 방법

isComposingtrue 라면 새로운 질문을 만들지 않고, isComposingfalse라면 새로운 질문을 만들어줘요.

const onKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
  if (e.key !== 'Enter') return;

  e.preventDefault();

  const target = e.target as HTMLInputElement;
  const { value: question } = target;

  if (!question || e.nativeEvent.isComposing) return;

  createQuestion(question);
  target.value = '';
};

화면 기록 2022-11-29 오전 10.58.53.mov