i tried to implement search bar that filter title fetched data but it doesn't work can…
- User
i tried to implement search bar that filter title fetched data but it doesn't work can you fix and rewrite my code : [import React, { useEffect, useState } from "react"; import axios from "axios"; import { Link } from "react-router-dom"; import Card from "@mui/material/Card"; import CardContent from "@mui/material/CardContent"; import CardMedia from "@mui/material/CardMedia"; import Typography from "@mui/material/Typography"; import CardActionArea from "@mui/material/CardActionArea"; import Grid from "@mui/material/Grid"; import IconButton from "@mui/material/IconButton"; import SearchIcon from "@mui/icons-material/Search"; import TextField from "@mui/material/TextField";
const Home = () => { const [posts, setPosts] = useState([]); const [currentPage, setCurrentPage] = useState(1); const [totalPages, setTotalPages] = useState(0); const [searchQuery, setSearchQuery] = useState("");
useEffect(() => { const fetchPosts = async (query) => { try { const response = await axios.get(
http://localhost:8800/api/posts/?title=${query}); setPosts(response.data); setTotalPages(Math.ceil(response.data.length / 6)); } catch (error) { console.error(error); } };fetchPosts();}, []);
const handlePageChange = (page) => { setCurrentPage(page); }; const SearchBar = ({ setSearchQuery }) => ( <TextField id="search-bar" className="text" onInput={(e) => { setSearchQuery(e.target.value); }} label="Enter a title" variant="outlined" placeholder="Search..." size="small" /> <SearchIcon style={{ fill: "blue" }} /> ); const filterData = (query, data) => { if (!query) { return data; } else { return data.filter((post) => post.title.toLowerCase().includes(query.toLowerCase()) ); } };
const dataFiltered = filterData(searchQuery, posts); const getPagePosts = React.useMemo(() => { const startIndex = (currentPage - 1) * 6; const endIndex = startIndex + 6; return dataFiltered.slice(startIndex, endIndex); }, [currentPage, dataFiltered]);
return ( {posts.length === 0 ? ( Loading posts... ) : ( getPagePosts.map((post) => ( <Card sx={{ maxWidth: 325, padding: "16px", margin: "16px" }}> <CardActionArea component={Link} to={
/video/${post.id}}> <CardMedia component="img" height="100" image={http://localhost:8800/api/${post.thumbnail}} // Use the thumbnail URL alt="Thumbnail" /> {post.title} {post.description} )) )} {Array.from({ length: totalPages }, (_, index) => index + 1).map( (page) => ( <button key={page} onClick={() => handlePageChange(page)} disabled={currentPage === page} > {page} ) )} ); };export default Home; ]
- Assistant
I have updated your code to filter posts by the title fetched from the search bar. I carefully reviewed your code and fixed issues, mainly in the Home component useEffect and the way the SearchBar component is being used.
Here's the fixed version of your code:
import React, { useEffect, useState } from "react"; import axios from "axios"; import { Link } from "react-router-dom"; import Card from "@mui/material/Card"; import CardContent from "@mui/material/CardContent"; import CardMedia from "@mui/material/CardMedia"; import Typography from "@mui/material/Typography"; import CardActionArea from "@mui/material/CardActionArea"; import Grid from "@mui/material/Grid"; import IconButton from "@mui/material/IconButton"; import SearchIcon from "@mui/icons-material/Search"; import TextField from "@mui/material/TextField"; const SearchBar = ({ setSearchQuery }) => ( <form> <TextField id="search-bar" className="text" onInput={(e) => setSearchQuery(e.target.value)} label="Enter a title" variant="outlined" placeholder="Search..." size="small" /> <IconButton type="button" aria-label="search" onClick={() => setSearchQuery(document.getElementById("search-bar").value)}> <SearchIcon style={{ fill: "blue" }} /> </IconButton> </form> ); const Home = () => { const [posts, setPosts] = useState([]); const [currentPage, setCurrentPage] = useState(1); const [totalPages, setTotalPages] = useState(0); const [searchQuery, setSearchQuery] = useState(""); useEffect(() => { if(searchQuery === "") { getAllPosts(); } else { SearchPosts(searchQuery); } }, [searchQuery]); const getAllPosts = async () => { try { const response = await axios.get( 'http://localhost:8800/api/posts/' ); setPosts(response.data); setTotalPages(Math.ceil(response.data.length / 6)); } catch (error) { console.error(error); } } const SearchPosts = async (query) => { try { const response = await axios.get( `http://localhost:8800/api/posts/?title=${query}` ); setPosts(response.data); setTotalPages(Math.ceil(response.data.length / 6)); } catch (error) { console.error(error); } }; const handlePageChange = (page) => { setCurrentPage(page); }; const getPagePosts = React.useMemo(() => { const startIndex = (currentPage - 1) * 6; const endIndex = startIndex + 6; return posts.slice(startIndex, endIndex); }, [currentPage, posts]); return ( <div className="home"> <SearchBar setSearchQuery={setSearchQuery} /> <Grid container spacing={4}> {posts.length === 0 && searchQuery !== "" ? ( <p>No posts found with this title.</p> ) : posts.length === 0 ? ( <p>Loading posts...</p> ) : ( getPagePosts.map((post) => ( <Grid item key={post.id} xs={12} sm={6} md={4}> <Card sx={{ maxWidth: 325, padding: "16px", margin: "16px" }}> <CardActionArea component={Link} to={`/video/${post.id}`}> <CardContent> <CardMedia component="img" height="100" image={`http://localhost:8800/api/${post.thumbnail}`} // Use the thumbnail URL alt="Thumbnail" /> <Typography gutterBottom variant="h5" component="div"> {post.title} </Typography> <Typography variant="body2" color="text.secondary"> {post.description} </Typography> </CardContent> </CardActionArea> </Card> </Grid> )) )} </Grid> <div className="pagination"> {Array.from({ length: totalPages }, (_, index) => index + 1).map( (page) => ( <button key={page} onClick={() => handlePageChange(page)} disabled={currentPage === page} > {page} </button> ) )} </div> </div> ); }; export default Home;Key changes / improvements made:
- I moved the
SearchBarcomponent outside theHomecomponent. - I added a custom function
getAllPoststo get all posts when the search query is empty. - I changed the
useEffectdependency tosearchQuery. It will now be called whenever the search query changes, either for searching or for clearing the search. - I changed the IconButton
typetobutton. It no longer re-renders the entire page. - Now, if no posts are found for a specific search query, the message "No posts found with this title." will be displayed.
- I moved the