Home > Back-end >  Handle new Redux for a global search filter
Handle new Redux for a global search filter

Time:10-24

I have a Navbar component where a search bar is located. Input should be taken through search bar and passed in a sibling component where blogs are located which are to be filtered through search functionality. It should be filtered onChange, means if I type "a" in searchBar, it should filter out blogNames which include "a".

Can somebody help me out with this?

CodePudding user response:

Considering you would be using redux & your component tree as follow:

    Home
   /    \
Navbar   Blogs

You can have blogReducer with initialState as:

const initialState = {
  searchedText: '', //Input Text
  blogs: [] //Your array of blogs
};

When input onChange is triggered in your Navbar component, dispatch an action which changes the state of searchedText state.

In Blogs component, use useEffect hook & add searchedText in its dependency array, so that when searchedText changes, the useEffect will be called & inside it you can fetch your blogs depending on this searched input.

useEffect(()=>{
  if(searchedText === '') return;
  //Your logic of filtering based on searchedText
},[searchedText])

CodePudding user response:

What you can do is (if you really want to use Redux for that), when your search terms changes you store it in the store. Then read them from your list to filter it anytime it changes

Here a the main steps :

  1. Create a reducer (let's call it SearchReducer) listening to a specific type like "SEARCH_TERM_CHANGES" and accepting a payload containing your search term value.

    export default function SearchReducer(state = initialState, action) {
    
      switch (action.type) {
          case "SEARCH_TERM_CHANGES" :
          return {
               searchTerm: action.payload
          }
        default : return state
    
    }
    
  2. When your search terms changes, you dispatch({type: "SEARCH_TERM_CHANGES",payload: yourSearchTermValue})

    const NavBar = () => {
        const dispatch= useDispatch()
        return <SearchBar onSearchTermChange={(yourSearchTermValue) => dispatch({type:  "SEARCH_TERM_CHANGES",payload: yourSearchTermValue})/>
    
    }
    

From now you should have your search terms always up to date in the store.

Now, in your BlogList that display some content, you can pass a string filter (your search term) as props , and filter you blog items based on this string filter

const BlogList = () => {
  // searchTerm is binded to the store so always up to date, and trigger a render anytime it changes
  const searchTerm = useSelector((state) => state.SearchReducer.searchTerm)
  const blogListItems = [{title:'blabla', id:1},{title:'somethingElse', id:2}] 

// You filter your items based on the search term
 return <BlogList items={blogItems.filter(item => item.title.includes(searchTerm)}} />
}
  • Related