| 1 |
import { useState } from "@wordpress/element"; |
| 2 |
|
| 3 |
const useSearch = (attributes) => { |
| 4 |
const { postType, selectedTaxonomy, initialPostDisplay } = attributes; |
| 5 |
const [allData, setAllData] = useState({ |
| 6 |
posts: [], |
| 7 |
remaining_posts: {}, |
| 8 |
}); |
| 9 |
|
| 10 |
const fetchPosts = async (searchText, term) => { |
| 11 |
try { |
| 12 |
if (!searchText) { |
| 13 |
return; |
| 14 |
} |
| 15 |
const query = { |
| 16 |
postType, |
| 17 |
s: searchText, |
| 18 |
term, |
| 19 |
taxonomyType: selectedTaxonomy, |
| 20 |
postLimit: initialPostDisplay?.value, |
| 21 |
page: "editor", |
| 22 |
}; |
| 23 |
return fetch(sp_smart_post_block_localize.searchRestUrl, { |
| 24 |
method: "POST", |
| 25 |
headers: { "Content-Type": "application/json" }, |
| 26 |
body: JSON.stringify(query), |
| 27 |
}) |
| 28 |
.then((res) => res.json()) |
| 29 |
.then((data) => { |
| 30 |
setAllData({ |
| 31 |
posts: data?.posts, |
| 32 |
remaining_posts: data?.remaining_posts, |
| 33 |
}); |
| 34 |
}); |
| 35 |
} catch (error) { |
| 36 |
console.error("Error fetching posts:", error.message); |
| 37 |
} |
| 38 |
}; |
| 39 |
|
| 40 |
return { ...allData, fetchPosts }; |
| 41 |
}; |
| 42 |
|
| 43 |
export default useSearch; |
| 44 |
|