1
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?

【React】useStateでローディング機能を実装

Posted at

はじめに

Reactの学習を進めていく中で、アウトプットとしてミニアプリを作成しています。
その際に初めてローディング機能の実装でつまづいたため記録として残します!

問題

データは表示されるけれどローディング中にローディングのテキストが表示されない

解決方法

更新関数であるsetIsLoadingにtrueかfalseなのかの状態を渡す。

App.js
import React, { useEffect } from "react";
import { useState } from "react";
import { getAllRecords } from "./utils/supabaseFunction";

export const App = () => {
  const [content, setContent] = useState("");
  const [time, setTime] = useState("");
  const [records, setRecords] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    const getRecords = async () => {
      setIsLoading(true);
      const records = await getAllRecords();
      setRecords(records);
      setIsLoading(false);
      console.log(records);
    };
    getRecords();
  }, []);

  return (
    <>
      {isLoading ? (
        <p>ローディング中</p>
      ) : (
        <div>
          {records.map((record, id) => (
            <div key={id} style={{ display: "flex", mt: "0" }}>
              <p style={{ p: "0" }}>{record.content}</p>
              <p style={{ px: "0" }}>{record.time}時間</p>
            </div>
          ))}
        </div>
      )}
    </>
  );
};

おわりに

理想通りの実装ができずつまづくと焦ってしまいがちですが、どこまで実装が正確にできているかの状況を整理しながらひとつひとつの実装を進めていくことが大事だなと気づきました。
また、まずは言葉で「何をしている時に(ex, データ取得中)」「ローディングはどんな状態なのか」などを説明できるよう実装していくことが解決への近道になると感じました。

1
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
1
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?