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

「読み込み中...」表示をuseEffectで実装

2
Posted at

はじめに

  • 外部ライブラリ使わない方法がないか色々試したが、クライアントからのデータフェッチだとuseEffectだった

問題

  • fetchまでに読み込み中表示が出ていない

解決

  • よくある感じで実装
import { useEffect, useState } from "react";
import { ulid } from "ulid";
import { createClient } from '@supabase/supabase-js'

const supabase = createClient(import.meta.env.VITE_SUPABASE_URL, import.meta.env.VITE_SUPABASE_PUB_KEY)

export const App = () => {

  const [hoge, setHoge] = useState('');
  const [piyo, setPiyo] = useState(0);
  const [hogeList, setHogeList] = useState([]);
  const [error, setError] = useState("");
  const [isLoading, setIsLoading] = useState(true);

  const onChangeHoge = (e) => {
    setHoge(e.target.value)
  }

  const onChangePiyo = (e) => {
    setPiyo(e.target.valueAsNumber)
  }

  const addHoge = () => {
    if (hoge === '' || piyo <= 0 || piyo === '') return;
    const newHoge = { id: ulid(), hoge, piyo };
    const newHogeList = [...hogeList, newHoge];
    setHogeList(newHogeList);
    setHoge('');
    setPiyo(0);
  }

  useEffect(() => {
    supabase.from('hoge_table').select('*')
      .then((response) => {
        setHogeList(response.data)
        setIsLoading(false)
      })
  }, [])

  return isLoading ? <p>読み込み中...</p> : (
    <>
      <h1>hogeリスト</h1>
      {error && <p style={{ color: 'red' }}>{error}</p>}
      <div>
        <label htmlFor="hoge">hoge: </label>
        <input type="text" id="hoge" name="hoge" value={hoge} onChange={onChangeHoge} />
      </div>
      <div>
        <label htmlFor="piyo">piyo: </label>
        <input type="number" id="piyo" name="piyo" value={piyo} onChange={onChangePiyo} />
      </div>
      <div>
        <p><span>入力されているhoge: </span>{hoge}</p>
      </div>
      <div>
        <p><span>入力されているpiyo: </span>{piyo ? piyo : 0}</p>
      </div>
      <div>
        <button onClick={addHoge}>登録</button>
      </div>
      <ul>
        {hogeList.map((item) => {
          const { id, hoge, piyo } = item;
          return (<li key={id}>{hoge}: {piyo}</li>)
        })}
      </ul>
    </>
  )
}

終わりに

  • ライブラリ使って実装するのが良さそう
2
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
2
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?