I'm building an e-commerce website with Strapi for the back end.
I went through the Strapi docs for filtering and now the filters seem to clash even though they produce no errors.
The code inside of the pointers seems to be the problem.
const List = ({ subCats, maxPrice, sort, catId }) => {
const { data, loading, error } = useFetch(
`/products?populate=*&[filters][categories][id]=${catId}${subCats.map(
(item) => `&[filters][sub_categories][id][$eq]=${item}`
)} &[filters][price][$lte]=${maxPrice}&sort=price:${sort}`
);
console.log(data);
return (
<div className="list">
{loading
? "loading"
: data?.map((item) => <Card item={item} key={item.id} />)}
</div>
);
};
It prevents the <List /> at the bottom of my Products page from appearing, but when I comment it out, the list appears, then the radio buttons and the range stop working. Does anyone know what the problem could be?
import React from "react";
import { useState } from "react";
import { useParams } from "react-router-dom";
import List from "../../components/List/List";
import useFetch from "../../hooks/useFetch";
import "./Products.scss";
const Products = () => {
const catId = parseInt(useParams().id);
const [maxPrice, setMaxPrice] = useState(50000);
const [sort, setSort] = useState(null);
const [selectedSubCats, setSelectedSubCats] = useState([]);
const { data, loading, error } = useFetch(
`/sub-categories?[filters][categories][id][$eq]=${catId}`
);
const handleChange = (e) => {
const value = e.target.value;
const isChecked = e.target.checked;
setSelectedSubCats(
isChecked
? [...selectedSubCats, value]
: selectedSubCats.filter((item) => item !== value)
);
};
return (
<div className="products">
<div className="left">
<div className="filterItem">
<h2>Product Categories</h2>
{data?.map((item) => (
<div className="inputItem" key={item.id}>
<input
type="checkbox"
id={item.id}
value={item.id}
onChange={handleChange}
/>
<label htmlFor={item.id}>{item.attributes.title}</label>
</div>
))}
</div>
<div className="filterItem">
<h2>Filter by price</h2>
<div className="inputItem">
<span>0</span>
<input
type="range"
min={0}
max={50000}
onChange={(e) => setMaxPrice(e.target.value)}
/>
<span>{maxPrice}</span>
</div>
</div>
<div className="filterItem">
<h2>Sort by</h2>
<div className="inputItem">
<input
type="radio"
id="asc"
value="asc"
name="price"
onChange={(e) => setSort("asc")}
/>
<label htmlFor="asc">Price (Lowest first)</label>
</div>
<div className="inputItem">
<input
type="radio"
id="desc"
value="desc"
name="price"
onChange={(e) => setSort("desc")}
/>
<label htmlFor="desc">Price (Highest first)</label>
</div>
</div>
</div>
<div className="right">
<img
className="catImg"
src="/src/assets/images/horrizontal-in-bed1.jpg"
alt=""
/>
<List catId={catId} maxPrice={maxPrice} sort={sort} subCats={selectedSubCats} />
</div>
</div>
);
};
export default Products;