| 1 |
import { useEffect, useState } from '@wordpress/element'; |
| 2 |
import apiFetch from '@wordpress/api-fetch'; |
| 3 |
import { select } from '@wordpress/data'; |
| 4 |
|
| 5 |
const useFetch = (path, dependencies = []) => { |
| 6 |
const [isLoading, setIsLoading] = useState(false); |
| 7 |
const [data, setData] = useState([]); |
| 8 |
const [error, setError] = useState(null) |
| 9 |
|
| 10 |
useEffect(() => { |
| 11 |
if (!path) { |
| 12 |
setData([]); |
| 13 |
setIsLoading(false); |
| 14 |
setError(null); |
| 15 |
return; |
| 16 |
} |
| 17 |
setIsLoading(true); |
| 18 |
apiFetch({ path }) |
| 19 |
.then((response) => { |
| 20 |
const data = response && response?.length > 0 ? response : []; |
| 21 |
setData(data); |
| 22 |
}) |
| 23 |
.catch((error) => { |
| 24 |
console.error("BetterDocs useFetch ERROR: ", error); |
| 25 |
setError(error); |
| 26 |
}) |
| 27 |
.finally(() => setIsLoading(false)); |
| 28 |
}, [path]) |
| 29 |
|
| 30 |
return { data, isLoading, error }; |
| 31 |
} |
| 32 |
|
| 33 |
export default useFetch |
| 34 |
|