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
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- JavaScript
- Estrellas
- 11.8k
- Forks
- 7.9k
- Merge medio
- 1 d 11 h
- PR fusionados (30 d)
- 11
Descripción
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.
Guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Línea de trabajo
Comienza revisando la documentación existente de React y el ejemplo de useSettings en el issue para identificar dónde debe incluirse la orientación sobre la carga de datos externos. La página terminada debe explicar el enfoque oficial para evitar la ausencia inicial de datos y cómo un hook puede garantizar que los datos estén disponibles antes de que los consumidores los utilicen.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- javascript, react
- Área
- documentation
- Tipo de issue
- Documentación
- Dificultad
- 4/5
- Tiempo estimado
- 3-5 días
- Estado de actividad
- Estancado
- Claridad
- Bastante claro
- Aptitud para principiantes
- 42/100