reactjs / reactjs/react.dev

A page on the docs site to show how to create a hook that loads data form an external source such that there would be no gap

オープン
#7,661 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

主要言語
JavaScript
スター
11.8k
フォーク
7.9k
平均マージ
1日 11時間
マージ済み PR(30日)
11

説明

Let's say I want to create a hook called useSettings. This hook will load settings once from an API and cache the data.

This is a sample code:

import {
    useEffect,
    useState,
} from "react"

let cache

const useSettings = () => {

    const [settings, setSettings] = useState(cache || [])

    useEffect(() => {
        if (cache) return
        callApi("/settings")
            .then(data => {
                setSettings(data)
                cache = data
            })
    }, [])

    const getSetting = (key, fallback) => {
        const setting = settings.find(i => i.key === key)
        if (!settings) {
            return fallback
        }
        return setting.value
    }

    return {
        getSetting
    }
}

export default useSettings

This works fine when the settings are loaded. But when a component uses this hook, there is an unpredictable time at the beginning when the settings are not loaded yet, and they get the fallback value.

I searched the docs and navigated the menu items. I could not find a page as a guide on how to remove that gap.

Please add a page for this purpose. Explain what is the react's official way to solve this problem. Explain how we can make sure that when we call a hook, we are guaranteed to get the data.

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まず、既存の React ドキュメントと issue 内の useSettings の例を確認し、外部データの読み込みに関するガイダンスをどこに配置すべきかを特定します。完成したページでは、初期データの欠落を避けるための公式なアプローチと、consumer がデータを使用する前に hook がデータの可用性を保証する方法を説明してください。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
javascript, react
領域
documentation
issue の種類
ドキュメント
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
42/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。