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 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

主要语言
JavaScript
星标
11.8k
派生
7.9k
平均合并
1 天 11 小时
30 天内合并 PR
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. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

首先查看现有的 React 文档和 issue 中的 useSettings 示例,以确定应在哪里加入有关加载外部数据的指导。完成后的页面应解释避免初始数据缺失的官方方式,以及 hook 如何在消费者使用数据之前保证数据可用。

由索引模型根据 Issue 内容生成。

评估

技术栈
javascript, react
领域
documentation
Issue 类型
文档
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
42/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。