STUDYING/React
[React] 로딩 띄우기와 통신 중 방해 금지 기능
sustronaut
2022. 5. 28. 14:10
1. 로딩
- 데이터가 아직 렌더링 안되었을 때 loading 뜨게 하기
import { Link } from "react-router-dom";
import useFetch from "../hooks/useFetch";
export default function DayList() {
const days = useFetch("http://localhost:3001/days");
if (days.length === 0) {
return <span>Loading...</span>;
}
...
}
2. 통신 중에 버튼 클릭시 반응없게 하기
const [isLoading, setIsLoading] = useState(false);
function onSubmit(e) {
e.preventDefault();
if (!isLoading) { //isLading이 false일 때,
setIsLoading(true); //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("생성이 완료 되었습니다");
history.push(`/day/${dayRef.current.value}`);
setIsLoading(false); //통신이 끝나면 false로 다시 바꿔줌
}
});
}
}
...
<button
style={{
opacity: isLoading ? 0.3 : 1,
}}
>
{isLoading ? "Saving..." : "저장"} //isLoading이 true 면 saving, false면 저장
</button>
출처 : 코딩앙마