Loading Spinner

Bin2·2022년 6월 4일
0

Loading Spinner

서버에서 데이터를 요청하는 등 시간이 걸리는 작업을 할 때
로딩 스피너를 화면에 렌더링 해주면 사용자 경험을 향상시킬 수 있다.

import './LoadingIndicator.css';

const LoadingIndicator = () => (
  <div className="lds-ring">
    <div />
    <div />
    <div />
    <div />
  </div>
);

export default LoadingIndicator;
.lds-ring {
  display: inline-block;
  position: relative;
  width: 54px;
  height: 54px;
}
.lds-ring div {
  box-sizing: border-box;
  display: block;
  position: absolute;
  width: 44px;
  height: 44px;
  margin: 6px;
  border: 6px solid #ff2058;
  border-radius: 50%;
  animation: lds-ring 1.2s cubic-bezier(0.5, 0, 0.5, 1) infinite;
  border-color: #ff2058 transparent transparent transparent;
}
.lds-ring div:nth-child(1) {
  animation-delay: -0.45s;
}
.lds-ring div:nth-child(2) {
  animation-delay: -0.3s;
}
.lds-ring div:nth-child(3) {
  animation-delay: -0.15s;
}
@keyframes lds-ring {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

로딩 스피너 컴포넌트를 만들어 주고, useState 훅을 이용한다.
fetch API로 서버에 요청을 보내기 전, 로딩 스피너를 렌더링 하고,
서버에서 데이터를 받아오면, 리스트 컴포넌트를 렌더링 한다.

const [isLoading, setIsLoading] = useState(false);

const Ingredients = () => {
  const [isLoading, setIsLoading] = useState(false);



  const addIngredientHandler = async (ingredient) => {
    setIsLoading(true);
    fetch(
      "...url",
      {
        method: "POST",
        body: JSON.stringify(ingredient),
        headers: {
          "Content-type": "applications/json",
        },
      }
    )
      .then((response) => {
        setIsLoading(false);
        return response.json();
      })
      .then((responseData) => {
        setUserIngredients((prevIngredients) => [
          ...prevIngredients,
          { id: responseData.name, ...ingredient },
        ]);
      });
  };

  
  return (
    <div className="App">
      {isLoading ? <LoadingIndicator /> : <IngredientList/>} 
    </div>
  );
};
profile
Developer

0개의 댓글