doc: change fetch url, added useState and functions

This commit is contained in:
Leon Xu committed 2023-01-30 18:01:43 -08:00
1 parent d4afd4236e
commit a975980619
1 file changed
+35 -3
+35 -3
View File
@@ -14,6 +14,8 @@ const Home = () => {
const [loading, setLoading] = useState(false);
const [allPosts, setAllPosts] = useState(null);
const [searchText, setSearchText] = useState("");
const [searchResults, setSearchResults] = useState(null);
const [searchTimeout, setSearchTimeout] = useState(null);
useEffect(() => {
const fetchPosts = async () => {
@@ -21,7 +23,7 @@ const Home = () => {
try {
const response = await fetch(
"https://dalle-image-generator-server.onrender.com/api/v1/post",
"https://a-s5dw.onrender.com/api/v1/post",
{
method: "GET",
headers: {
@@ -43,6 +45,26 @@ const Home = () => {
fetchPosts();
}, []);
const handleSearchChange = (e) => {
clearTimeout(searchTimeout);
setSearchText(e.target.value);
setSearchTimeout(
setTimeout(() => {
const searchResults = allPosts.filter((item) =>
item.name
.toLowerCase()
.includes(
searchText.toLowerCase() ||
item.prompt.toLowerCase().includes(searchText.toLowerCase())
)
);
setSearchResults(searchResults);
}, 500)
);
};
return (
<section className="max-w-7xl mx-auto">
<div>
@@ -56,7 +78,14 @@ const Home = () => {
</div>
<div className="mt-16">
<FormField />
<FormField
labelName="Search posts"
type="text"
name="text"
placeholder="Search Posts"
value={searchText}
handleChange={handleSearchChange}
/>
</div>
<div className="mt-10">
@@ -74,7 +103,10 @@ const Home = () => {
)}
<div className="grid lg:grid-cols-4 sm:grid-cols-3 xs:grid-cols-2 grid-cols-1 gap-3">
{searchText ? (
<RenderCards data={[]} title="No search results found" />
<RenderCards
data={searchResults}
title="No search results found"
/>
) : (
<RenderCards data={allPosts} title="No posts found" />
)}