[React] 코딩앙마 리액트 기초강좌 #16 마치며

zzzzsb·2022년 5월 30일
0

React 강좌

목록 보기
12/12

#16 마치며

네트워크 환경 느릴때 처리

개발자도구 > Network > Slow 3G로 설정해놓고 테스트 해보자

useFetch.js

const [data, setData] = useState([]);

초기값이 [] 이므로, 배열 length가 0일때 Loading… 을 출력해보자

DayList.js

if(days.length === 0){
    return <span>Loading...</span>
}

단어 추가시 통신중일때는 저장버튼 클릭하지 못하도록

CreateWord.js

import { useRef, useState } from 'react';
import { useNavigate } from "react-router-dom";
import useFetch from '../hooks/useFetch';

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

  function onSubmit(e) {
    e.preventDefault(); // 기본 새로고침 막아줌
  
    if(!isLoading){
      setIsLoading(true);
      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('생성 완료되었습니다');
          navigate(`/day/${dayRef.current.value}`);
          setIsLoading(false);
        }
      });
    }
  }

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

  return (
    <form onSubmit={onSubmit}>
      <div className="input_area">
        <label>Eng</label>
        <input type="text" placeholder="computer" ref={engRef} />
      </div>
      <div className="input_area">
        <label>Kor</label>
        <input type="text" placeholder="컴퓨터" ref={korRef} />
      </div>
      <div className="input_area">
        <label>Day</label>
        <select ref={dayRef}>
          {days && days.map(day => (
            <option key={day.id} value={day.day}>
              {day.day}
            </option>
          ))}
        </select>
      </div>
      <button
        style={{
          opacity: isLoading ? 0.3 : 1,
        }}
      >
        {isLoading ? "Saving..." : "저장"}
      </button>
    </form>
  );
}
  • isLoading 상태 생성

  • isLoading이 false일때(로딩중 아닐때) 단어 출력

  • 단어 출력전에는 로딩중이므로 setIsLoading(true)해줌

  • 단어 출력후에는 로딩완료이므로 setIsLoading(false)해줌

  • 버튼에 로딩중일때는 Saving.. 이라고 투명도 준 버튼으로 출력되도록 수정함

profile
성장하는 developer

0개의 댓글