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
Nessuno ha ancora preso questa issue.
- Lingua principale
- JavaScript
- Stelle
- 11.8k
- Fork
- 7.9k
- Merge medio
- 1g 11h
- PR unite (30g)
- 11
Descrizione
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.
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia esaminando la documentazione esistente di React e l'esempio useSettings nell'issue per identificare dove inserire le indicazioni sul caricamento di dati esterni. La pagina completata dovrebbe spiegare l'approccio ufficiale per evitare l'assenza iniziale di dati e come un hook possa garantire la disponibilità dei dati prima che i consumer li utilizzino.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- javascript, react
- Ambito
- documentation
- Tipo di issue
- Documentazione
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 42/100