From e005e8a12b9ba22af72455ec88656acd35f7b944 Mon Sep 17 00:00:00 2001 From: lestertai8 Date: Mon, 20 Jan 2025 13:57:38 -0600 Subject: [PATCH] also added search bar to public feed --- src/components/PublicFeed/PublicFeed.jsx | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/src/components/PublicFeed/PublicFeed.jsx b/src/components/PublicFeed/PublicFeed.jsx index 8fc67bd..125e601 100644 --- a/src/components/PublicFeed/PublicFeed.jsx +++ b/src/components/PublicFeed/PublicFeed.jsx @@ -1,6 +1,7 @@ import React, { useState, useEffect } from 'react'; import Post from '../Post/Post'; import NavigationBar from '../NavigationBar/NavigationBar'; +import CourseSelect from '../CourseSelect/CourseSelect'; import RestoreIcon from '@mui/icons-material/Restore'; import PeopleIcon from '@mui/icons-material/People'; import PublicIcon from '@mui/icons-material/Public'; @@ -41,6 +42,9 @@ const fake_friends = ["Alice", "Bob", "Charlie", "David"]; function PublicFeed() { const [posts, setPosts] = useState([]); + const [search, setSearch] = useState(); + const [filteredposts, setFilteredposts] = useState([]); + // useEffect runs every time the component is rendered useEffect(() => { // wait for all posts from database to be fetched @@ -55,6 +59,18 @@ function PublicFeed() { fetchPosts(); }, []); + // Source: https://www.freecodecamp.org/news/filter-arrays-in-javascript/ + // How to filter an array by search term ^ + // https://www.geeksforgeeks.org/how-to-build-a-search-filter-using-react-hooks/ + useEffect(() => { + if (search) { // if there's something in the search bar + setFilteredposts(posts.filter(post => post.course_name.toLowerCase().includes(search))) + } + else { + setFilteredposts(posts) // retrieve all if the search bar isn't being used + } + }, [search, posts]); // must define the states that cause re-rendering + const [value, setValue] = React.useState(1); const handleChange = (event, newValue) => { @@ -69,12 +85,13 @@ function PublicFeed() { } component={Link} to="/feed" /> } component={Link} to="/public" /> + - { posts.length === 0 ? - (

Loading posts...

) : - (posts + { filteredposts.length === 0 ? + (

No results found...

) : + (filteredposts .slice() .sort((a, b) => b.date.seconds - a.date.seconds).map((post) =>