СК
Size: a a a
СК
СК
ЮЧ
ЮЧ
const [user, error, loading, refresh, cancel] = useFetchUser(id)
.D
ЮЧ
const useFetchUser = id => {
const [result, setResult] = useState()
const [error, setError] = useState(null)
const [loading, setLoading] = useState(false)
const fetch = useCallback(async, () => {
try {
setError(null)
setLoading(true)
const response_ = await axios.get(`/users/${id}`)
setResponse(response_)
} catch (error) {
setError(error)
} finally {
setLoading(false)
}
}, [id])
useEffect(() => {
fetch()
}, [id])
return [result, error, loading, fetch]
}
ait axios.get(`/users/${id}`),
этот шаблон легко превращается в такую фабрику:nst createFetchHook = (factory, deps) => {const useFetchUser = createFetchHook(() => axios.get(`/users/${id}`), [id])
return (...args) => {
const [result, setResult] = useState()
const [error, setError] = useState(null)
const [loading, setLoading] = useState(false)
const fetch = useCallback(async, () => {
try {
setError(null)
setLoading(true)
const response_ = await factory(...args)
setResponse(response_)
} catch (error) {
setError(error)
} finally {
setLoading(false)
}
}, deps)
useEffect(() => {
fetch()
}, deps)
return [result, error, loading, fetch]
}
}
ЮЧ
ЮЧ
D
ЮЧ
1
СК
ИМ
YB
ЮЧ
// eslint-disable-line react-hooks/exhaustive-deps.
ЮЧ
ЮЧ
ИМ
// eslint-disable-line react-hooks/exhaustive-deps.
ЮЧ
exhaustive-deps
, а другая?