How to filter products in react based on search input in real time from the local state ?
I am trying to make real-time search functionality with the product stores in the local state. For that, I have created a function that takes queries from the search input and storing in a q variable of the handle search function. query and setQuery are context states. this working perfectly but when I remove some letters, then the function is not filtering products based on the remaining letters. Let's say I have two products called belt and bolt, and when I type bolt it shows the bolt product but when I remove some letters and stop at "b" then it's not showing me both the product based on the letters. And when I remove all the letters it shows all the products. I am a bit confused about how to tackle this. If anybody has some suggestion please do let me know.
4 Replies
I guess this might be because you have already updated your localProducts list with only one element ie bolt. You should filter on the inital list ie the list containing all the items
localProducts initially have all the products by default I am filtering from localProducts only. and its working fine sir, but only problem its not filtering when remove some letters
Store localProduct in some other variable and filter over that
sir initially when the app fetches products it gets stored in the products variable that is in context. and in the product page when I am just assigning the products to localProducte state and playing with that.
const [localProducts, setLocalProdcuts] = useState(products)
and passing the localProducts to the productcard component