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
還沒有人認領這個 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.
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
首先查看現有的 React 文件和 issue 中的 useSettings 範例,以確定應在哪裡加入有關載入外部資料的指引。完成後的頁面應說明避免初始資料缺失的官方方式,以及 hook 如何在消費者使用資料之前保證資料可用。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- javascript, react
- 領域
- documentation
- Issue 類型
- 文件
- 難度
- 4/5
- 預估耗時
- 3-5 天
- 活躍度
- 停滯
- 描述清晰度
- 基本清楚
- 新手友好度
- 42/100