This logic is about filtering houses based on filters (such as purpose, price etc) when I change the filters nothing happens (no url change) or no error on console. It looks like data is not being passed to searchProperties.
I am unable to find any solution.
Note: Ignore comments.
import classes from "./FilterProperties.module.css";
import { useState } from "react";
import { filterData, getFilterValues } from "../../lib/filterData";
import {
useLocation,useSearchParams, useNavigate} from "react-router-dom";
import DropDown from "./DropDown";
const FilterProperties = () => {
const location = useLocation();
const [filters, setFilters] = useState(filterData);
const [searchParams, setSearchParams] = useSearchParams();
const navigate = useNavigate();
const searchProperties = (filterValues) => {
const path = location.pathname;
console.log(path);
const query = searchParams.get("query");
console.log(query); // undefined
const values = getFilterValues(filterValues); // error
// console.log(values);
values.forEach((item) => {
setSearchParams[item.name] = item.value;
});
navigate({ pathname: path, query });
};
return (
<div className={classes.item}>
{filters.map((filter) => (
<DropDown
key={filter.queryName}
placeholder={filter.placeholder}
filter={filter}
onChange={(e) => {
searchProperties({ [filter.queryName]: e.target.value });
}}
/>
))}
</div>
);
};
export default FilterProperties;
CodePudding user response:
It seems you are misusing the setSearchParams
function. The useSearchParams
hook returns a URLSearchParams
object and a setSearchParams
function that works similarly to the navigate
function but only updates the search part of the URL. The basic gist is that you only need to iterate over the filter key-value pairs, update the searchParams
object, and then issue the imperative navigation with the updated query parameters.
Example:
...
const [searchParams, setSearchParams] = useSearchParams();
...
const searchProperties = (filterValues) => {
const values = getFilterValues(filterValues); // *
values.forEach(({ name, value }) => {
searchParams.set(name, value); // <-- set query parameter value
});
setSearchParams(searchParams); // <-- update query params
};
* Note: I am assuming that getFilterValues(filterValues)
functions and returns all the filter key-value pairs the UI is working with.