개발자도구 > Network > Slow 3G로 설정해놓고 테스트 해보자
const [data, setData] = useState([]);
초기값이 [] 이므로, 배열 length가 0일때 Loading… 을 출력해보자
if(days.length === 0){
return <span>Loading...</span>
}
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.. 이라고 투명도 준 버튼으로 출력되도록 수정함