update useRequest

This commit is contained in:
SrGooglo 2025-05-21 19:11:12 +00:00
parent 7c11af2643
commit 8e26ab1008

View File

@ -1,31 +1,42 @@
import React from "react" import React from "react"
export default (method, ...args) => { export default (method, ...args) => {
const [loading, setLoading] = React.useState(true) const [loading, setLoading] = React.useState(true)
const [result, setResult] = React.useState(null) const [result, setResult] = React.useState(null)
const [error, setError] = React.useState(null) const [error, setError] = React.useState(null)
if (typeof method !== "function") { if (typeof method !== "function") {
return [() => {}, null, new Error("Method is not a function"), () => {}] return [() => {}, null, new Error("Method is not a function"), () => {}]
} }
const makeRequest = (...newArgs) => {
method(...newArgs)
.then((data) => {
setResult(data)
setLoading(false)
})
.catch((err) => {
setError(err)
setLoading(false)
})
}
React.useEffect(() => { const makeRequest = (...newArgs) => {
makeRequest(...args) method(...newArgs)
}, []) .then((data) => {
setResult(data)
setLoading(false)
})
.catch((err) => {
console.error(err)
setError(err)
setLoading(false)
})
}
return [loading, result, error, (...newArgs) => { React.useEffect(() => {
setLoading(true) makeRequest(...args)
makeRequest(...newArgs) }, [])
}]
} return [
loading,
result,
error,
(...newArgs) => {
setLoading(true)
makeRequest(...newArgs)
},
() => {
setLoading(true)
makeRequest(...args)
},
]
}