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?

supabaseとReact19のuse()フックを使ってデータフェッチする

2
Posted at

はじめに

  • supabaseからフェッチする値は表示のみの想定
  • 今までswrかtanstack、useEffectでしかデータフェッチしたことなかった

問題

  • 失敗すると無限ループしたり、データフェッチできなかった

解決

  • こんな感じで解決
const supabase = createClient('import.meta.env.VITE_SUPABASE_API_URL', import.meta.env.VITE_SUPABASE_PUB_KEY)

const fetchHogeRecords =  async () => {
    return await supabase.from('hoge_records').select('*')
}

const fetchedHogeRecordsPromise = fetchHogeRecords()

export const App = () => {
  const learnRecordsPromise = use(fetchedLearnRecordsPromise)
  const learnRecords = learnRecordsPromise.data

  // 〜省略 mapでjsxの中を回したりする〜
}

終わりに

use() フックについて

Promiseの復習

具体的なuse() フックを使ったデータフェッチの例

React公式その他データフェッチ手法について

余談、メモ

  • 色々試してる時、console.logを変なところに残したままにしていて、文字入力ごとになぜかapiをフェッチしにいってる?と思ったがdev toolsのnetworkタブを見たら通信していなくて気づいた
  • promiseを「結果返ってくるまで待つ」よりも正確な言語化したい
  • use()の使い方合ってるかわからない。promiseは別ファイルのただの関数の返り値としてとって渡すのだろうか
  • 更新必要なデータがたくさんある画面で「読み込み中...」表示にもSuspenseと組み合わせてつかおうと思ったけどダメそう。それはuseEffectでやった。実際はフレームワークの機能とかreactのフックを組み合わせて実装するみたい https://react.dev/learn/you-might-not-need-an-effect#how-to-remove-unnecessary-effects
2
0
1

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?