import React, { useEffect, useState } from "react";
import { Form, Row, Col, Button } from "react-bootstrap";
import { useParams, useNavigate } from "react-router-dom";
const FilterComponent = ({ categories, brands }) => {
const { keyword} = useParams();
const [category, setCategory] = useState(null);
const [brand, setBrand] = useState(null);
const [rating, setRating] = useState(null);
const navigate = useNavigate();
useEffect(() => {
const params = new URLSearchParams(window.location.search);
const param1 = params.get("category");
const param2 = params.get("brand");
const param3 = params.get("rating");
// Only update state if the parameters are not null
if (param1 !== null) {
setCategory(param1);
}
if (param2 !== null) {
setBrand(param2);
}
if (param3 !== null) {
setRating(param3);
}
console.log(param1);
console.log(param2);
console.log(param3);
console.log(category);
console.log(brand);
console.log(rating);
}, [category, brand, rating, keyword, navigate ]);
const handleCategoryChange = (event) => {
const selectedCategory = event.target.value;
setCategory(selectedCategory);
console.log('category selected 1:', selectedCategory);
if (selectedCategory){
console.log('category selected 2:', selectedCategory);
console.log('URL Parameters:', keyword);
console.log(category)
navigate(`/search/${keyword}/filter?category=${selectedCategory}&brand=${brand}&rating=${rating}`);
}
};
const handleBrandChange = (event) => {
const selectedBrand = event.target.value;
setBrand(selectedBrand);
if (selectedBrand){
navigate(`/search/${keyword}/filter?category=${category}&brand=${selectedBrand}&rating=${rating}`);
}
};
const handleRatingChange = (event) => {
const selectedRating = Number(event.target.value);
setRating(selectedRating);
if (selectedRating){
navigate(`/search/${keyword}/filter?category=${category}&brand=${brand}&rating=${selectedRating}`);
}
};
const handleClearFilters = () => {
setCategory("");
setBrand("");
setRating("");
};
return (
<div>
<h2>Filter By</h2>
<Form>
<Row className="d-flex flex-column ">
<Col>
<Button variant="secondary" onClick={handleClearFilters}>
Clear Filters
</Button>
</Col>
<Col>
<Form.Group controlId="category">
<Form.Label>Category</Form.Label>
<Form.Control
as="select"
value={category}
onChange={handleCategoryChange}
>
<option value="">All Categories</option>
{categories.map((category, index) => (
<option key={index} value={category}>
{category}
</option>
))}
</Form.Control>
</Form.Group>
</Col>
<Col>
<Form.Group controlId="brand">
<Form.Label>Brand</Form.Label>
<Form.Control
as="select"
value={brand}
onChange={handleBrandChange}
>
<option value="">All Brands</option>
{brands.map((brand, index) => (
<option key={index} value={brand}>
{brand}
</option>
))}
</Form.Control>
</Form.Group>
</Col>
<Col>
<Form.Group controlId="rating">
<Form.Label>Rating</Form.Label>
<Form.Control
as="select"
value={rating}
onChange={handleRatingChange}
>
<option value="">All Ratings</option>
{[...Array(5)].map((_, index) => (
<option key={index + 1} value={index + 1}>
{index + 1} Stars
</option>
))}
</Form.Control>
</Form.Group>
</Col>
</Row>
</Form>
</div>
);
};
export default FilterComponent;
The query
getProducts: builder.query({
query: ({ keyword, pageNumber, category, brand, rating}) => ({
url: PRODUCTS_URL,
params: {
keyword,
pageNumber,
category,
brand,
rating,
},
}),
providesTags: ["Products"],
keepUnusedDataFor: 5,
}),
Front end routing
const router = createBrowserRouter(
createRoutesFromElements(
<Route path="/" element={<App />}>
<Route index={true} path="/" element={<HomeScreen />} />
<Route path="/search/:keyword" element={<HomeScreen />} />
<Route path="/search/:keyword/filter" element={<HomeScreen />} />
)
)
In the backend i tried to console the req.query it is showing undefined undefined undefined
// @desc Fetch all products
// @route GET /api/products
// @access Public
const getProducts = asyncHandler(async (req, res) => {
const { category, brand, rating } = req.query; // Get the filter parameters from the query string
console.log(category, brand, rating);
im getting undefined undefined undefined why?
suppose if selected
"electronics" as category
"apple" as brand
"4 star" as rating
I’m expecting in the backend
electronics apple 4 star
but what im actually getting
undefined undefined undefined
and "keyword" is successfully is getting in the backend
i dont understand why it is not getting into the backend controller
is there anyone to solve my doubt ???
2
Answers
The issue stems from parameters like
category
,brand
, andrating
beingundefined
in the backend despite being sent from the frontend. To resolve:req.query
.Debug by examining network requests, confirming frontend URL construction, and checking backend parsing. Fixing these points should resolve the issue of
undefined
parameters in the backend.I’m pretty sure the issue is related to you setting the values as parameters and not in the query. In the back-end you are reading the query.
I believe moving the variables from params to query should fix the issue. However, it depends on the string stored in PRODUCTS_URL. Assuming PRODUCTS_URL is something inline of
/api/products/{keyword}
, following code snippet should fix the issue: