| 1 |
import { useQuery } from "@tanstack/react-query"; |
| 2 |
import { useEffect, useState } from "react"; |
| 3 |
import apiFetch from "@wordpress/api-fetch"; |
| 4 |
import { addQueryArgs } from "@wordpress/url"; |
| 5 |
|
| 6 |
const useAuthorsQuery = (queryKeyValue, authorsDefaultParams) => { |
| 7 |
const [authorParams, setAuthorParams] = useState(authorsDefaultParams); |
| 8 |
const [authors, setAuthors] = useState([]); |
| 9 |
const [isNextPageAvailable, setNextPageAvailable] = useState(true); |
| 10 |
|
| 11 |
const { isLoading:usersLoading, data:usersData } = useQuery([queryKeyValue, authorParams], ({queryKey}) => { |
| 12 |
let [_,params] = queryKey; |
| 13 |
return apiFetch({ |
| 14 |
path: addQueryArgs(`wp/v2/users`, params), |
| 15 |
method: "GET", |
| 16 |
parse: false, |
| 17 |
}).then((data) => { |
| 18 |
return data.json(); |
| 19 |
}).then((result) => { |
| 20 |
if(result?.length > 0) { |
| 21 |
setNextPageAvailable(true); |
| 22 |
} else { |
| 23 |
setNextPageAvailable(false); |
| 24 |
} |
| 25 |
return result; |
| 26 |
}); |
| 27 |
}, { |
| 28 |
refetchOnWindowFocus:false |
| 29 |
}); |
| 30 |
|
| 31 |
useEffect(() => { |
| 32 |
if( !usersLoading ) { |
| 33 |
const authorOptions = usersData?.map((author) => ({ |
| 34 |
value: author.id, |
| 35 |
label: author.name, |
| 36 |
})); |
| 37 |
setAuthors((prev) => { |
| 38 |
return [...prev, ...authorOptions] |
| 39 |
}); |
| 40 |
} |
| 41 |
}, [usersLoading, usersData]); |
| 42 |
|
| 43 |
return {usersLoading, setAuthorParams, authorParams, setAuthors, authors, isNextPageAvailable} |
| 44 |
} |
| 45 |
|
| 46 |
export default useAuthorsQuery; |
| 47 |
|