skip to Main Content

I am encountering an issue while attempting to filter products based on a query parameter in a React component. I have a Main component that fetches products from a context and extracts a query parameter from the URL using useLocation from react-router-dom. I then use useState and useEffect hooks to filter the products based on this query parameter.

The filtering logic seems correct, as I’m checking if the query parameter is undefined and, if so, setting FilteredProducts to the entire products array. However, despite this logic, the component is not displaying all products when query is undefined. While it is filtering the products for the categories but not showing the entire products when i visit on the ‘/’ or route. Also when ever I refresh page in certain query (not undefined) it then show loading Plz Help..

import React, { useContext, useEffect, useState } from "react";
import Product from "./Product";
import { ProductContext } from "../utils/Context";
import Loading from "./Loading";
import { useLocation } from "react-router-dom";

function Main() {
  const { products } = useContext(ProductContext);
  const { search } = useLocation();
  let query = decodeURIComponent(search.split("=")[1]);
  const [FilteredProducts, setFilteredProducts] = useState([]);
  useEffect(() => {
    console.log("component createed");
    if (products) {
      if (query) {
        setFilteredProducts(
          products.filter((product) => product.category == query)
        );
      } else {
        setFilteredProducts(products);
      }
    }
    
  }, [query]);

  return FilteredProducts.length == 0 ? (
    <Loading />
  ) : (
    <div className="w-[80%] px-5 py-28 overflow-x-hidden overflow-y-auto">
      <div className="flex justify-center gap-4  flex-wrap">
        {FilteredProducts.map((product) => (
          <Product key={product.id} product={product} />
        ))}
      </div>
    </div>
  );
}

export default Main;

I tried filtering products based on a query parameter in a React component. I expected the component to display all products when the query parameter is undefined, and to display filtered products when the query parameter is defined (which is working).

2

Answers


  1. Looks like you have not added products as dependency in useEffect hook.
    Try adding the products as dependency in useEffect.

    useEffect(() => {
       // remaining code
    }, [query, products])
    
    Login or Signup to reply.
  2. try using query in useState

    const [query, setQuery] = useState("")
    

    and set its value in useEffect

    useEffect(()=>{
        setQuery(decodeURIComponent(search.split("=")[1]))
    },[])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search