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
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- JavaScript
- Sterne
- 11.8k
- Forks
- 7.9k
- Ø Merge
- 1 T. 11 Std.
- Gemergte PRs (30 T.)
- 11
Beschreibung
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.
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne damit, die bestehende React-Dokumentation und das useSettings-Beispiel im Issue zu überprüfen, um zu ermitteln, wo Hinweise zum Laden externer Daten hingehören. Die fertige Seite sollte den offiziellen Ansatz zur Vermeidung der anfänglichen Datenlücke erklären und wie ein Hook die Datenverfügbarkeit garantieren kann, bevor Consumer sie verwenden.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- javascript, react
- Bereich
- documentation
- Issue-Typ
- Dokumentation
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 42/100