맨 땅에 프론트엔드 개발자 되기

React Input에 defaultValue를 key와 함께 설정하기 - 에러 기록 본문

코딩 공부 일지/React JS

React Input에 defaultValue를 key와 함께 설정하기 - 에러 기록

헬로코딩 2022. 8. 4. 20:26
728x90

오늘 만난 에러는 폼 양식 수정 페이지를 만들면서 마주했다.

폼 양식이 있고, 비동기 API로 기존 정보를 불러와 input 텍스트 타입 안에 defaultValue를 설정하는 것이었다. 당연히 수정이 가능해야 하므로 value로 설정하지 않고, defaultValue로 설정했다.

 

플로우는 이러하다.

  1. useParams로 수정할 아이템의 id 값을 읽어들인다.
  2. redux-saga를 이용해 비동기 API에 id 값을 넘겨 기존 정보를 요청한다.
  3. redux의 상태 값에 받은 정보를 업데이트 하면 상태가 업데이트 되므로 리렌더링이 일어나 defaultValue 값에 설정해 둔 상태가 리렌더링 되어 기존 정보를 input 값에 보여준다.

 

이것이 나의 시나리오였다.

그러나 웬걸 defaultValue가 불러와지지 않는 것이었다.

 

오리지널 코드

import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { itemInfoInit } from "modules/List";
import { useParams } from "react-router-dom";

export default function Example() {
  const { id } = useParams();
  const dispatch = useDispatch();
  const { itemInfo } = useSelector(state => state.list);

  useEffect(() => {
    dispatch(itemInfoInit(id));
  }, [dispatch, id]);

  return (
    <form>
      <ul className="form-list">
        <li className="form-item">
          <label className="form-label">제목</label>
          <input type="text" name="title" id="title" placeholder="제목을 입력해주세요."
            defaultValue={itemInfo.title}
          />
        </li>
        <li className="form-item">
          <label className="form-label">내용</label>
          <textarea name="content" id="content" placeholder="내용을 입력해주세요."
            defaultValue={itemInfo.content}
          ></textarea>
        </li>
      </ul>
    </form>
  )
}

 

해결 방법을 찾기 위해 서치를 하던 중 다음과 같은 글을 읽게 되었다.

 

React input defaultValue doesn't update with state

I'm trying to create a simple form with react, but facing difficulty having the data properly bind to the defaultValue of the form. The behavior I'm looking for is this: When I open my page, the Text input field should be filled in with th

www.querythreads.com

 

 

How to fix React input defaultValue doesn't update with state with JavaScript? - The Web Dev

Spread the love Related Posts How to update array state in React Native?Sometimes, we want to update array state in React Native. In this article, we'll look… How to fix input losing focus when rerendering with React?Sometimes, we want to fix input losin

thewebdev.info

요약하자면, defaultValue 는 initial load 즉, 맨 처음 로드를 위한 것으로 별도의 요청을 하지 않는 한 리렌더링이 되지 않는다. 그래서 별도의 요청 즉, 렌더링이 일어나도록 조건을 걸려면 key 값을 주어서 변경을 인식하도록 만들면된다.

 

수정된 코드

import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { itemInfoInit } from "modules/List";
import { useParams } from "react-router-dom"

export default function Example() {
  const { id } = useParams();
  const dispatch = useDispatch();
  const { itemInfo } = useSelector(state => state.list);

  useEffect(() => {
    dispatch(itemInfoInit(id));
  }, [dispatch, id]);

  return (
    <form>
      <ul className="form-list">
        <li className="form-item">
          <label className="form-label">제목</label>
          <input type="text" name="title" id="title" placeholder="제목을 입력해주세요."
            defaultValue={itemInfo.title}
            key={itemInfo.title}
          />
        </li>
        <li className="form-item">
          <label className="form-label">내용</label>
          <textarea name="content" id="content" placeholder="내용을 입력해주세요."
            defaultValue={itemInfo.content}
            key={itemInfo.content}
          ></textarea>
        </li>
      </ul>
    </form>
  )
}

이렇게 코드를 수정했더니 defaultValue가 잘 불러와졌다.

 

에러 해결 끝!!

728x90