I’m trying to filter the data by select, but I don’t know why my code doesn’t work. In the console I can see that it correctly shows me the selected items (option). I noticed that the problem is onChange, which shows undefined in the console even though the value is correctly shown.
<FormLabel htmlFor="type">Type</FormLabel>
<Select
value={selectedType}
onChange={(e) => setSelectedType(e.target.value)}
id="type"
>
<option value="mtb">MTB bike</option>
<option value="country">Country</option>
</Select>
</FormControl>
<Box className="grid grid-cols-3 gap-6">
{currentProducts.map((data) => (
<Card key={data.id} maxW="sm">
// rest code
const currentProducts = selectedType ? products.filter((item) => item.type === selectedType) : products.slice(startIndex, startIndex + productsPerPage)
const [selectedType, setSelectedType] = useState("");
export const products: Products[] = [
{
id: 1,
price: 1800,
type: "country",
},
export interface Products {
id: number;
price: number;
type: string;
}
2
Answers
You have to use useEffect / Upon choosing from select, call a function update the selectedType state and the currentProducts.
Apparently there is nothing incorrect in the code you have shared. When I tried to replicate the issue with the code below, it did not fail, and it worked well. I request you may please go through this code use it to match it with yours, perhaps it may help you to spot the cause of failure. Or if you can share your original code via Github, I shall take a detailed look.
App.js
npm list
Test run: