0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Reactでローディングの作り方

Posted at

Reactでローディングの作り方

API通信をするときなどに、待つ時間が長いとローディング状態を表示する必要があるときもありますよね〜

そんな時には、useStateでローディング状態を管理します!

まずは

API通信するreactコンポーネントを用意します!

今回はjsonplaceholderを使います。
便利なのでぜひ!→https://jsonplaceholder.typicode.com/

import React, { useState, useEffect } from "react";

const Api = () => {
  const [data, setData] = useState(undefined);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then((res) => res.json())
      .then((json) => {
        setData(json)
      })
      .catch(() => {
        alert("error")
      });
  }, []);


  // ここを変更
  return (
    <>
      {data === undefined ? "" : <div>{data[0].title}</div>}
    </>
  );
};

export default Api;

これでdataの1番目のタイトル名を表示するAPIが叩けましたね!

useStateでisLoding状態を管理するstateを設置!

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

isLodingがtrueの時はローディング中です。

api通信をしている箇所でtrue,false切り替えをする

  useEffect(() => {
    setIsLoading(true);
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then((res) => res.json())
      .then((json) => {
        setData(json)
        setIsLoading(false);
      })
      .catch(() => {
        alert("error")
        setIsLoading(false);
      });
  }, []);

三項演算子でローディング時と非ローディング時の表示を設置

{isLoading ? <p>ローディング中</p> : <p>終わりだピョーン</p>}

これでローディング状態を管理できますね!
上手く使えばローディングアニメーションだったり、コンポーネント単位で表示したりすることもできそうです!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?