Why does the e.target.value === 0
and e.target.value === 21
not work?
I select --choose an option--
, it return [], I expect return all id.
I select ≥21
, it return id 19,16,20,21, I expect return id 21, 27,27,30.
but I select 0-10 and 11-20, they work
const Test = () => {
const data = [
{
date: '2005',
id: 27,
},
{
date: '2005',
id: 27,
},
{
date: '2003',
id: 3,
},
{
date: '2001',
id: 19,
},
{
date: '2000',
id: 4,
},
{
date: '2014',
id: 30,
},
{
date: '2011',
id: 16,
},
{
date: '2011',
id: 10,
},
{
date: '2011',
id: 20,
},
{
date: '2011',
id: 21,
},
];
const [newId, setNewId] = useState(data);
const [filter, setFiltered] = useState();
const handle = (e) => {
const aa = newId.filter((item) =>
e.target.value === 0
? item.id > 0 //return all id, doesn't work
: e.target.value === 21
? item.id >= 21 //return id >= 21, doesn't work
: item.id <= e.target.value && item.id > e.target.value - 10
);
setFiltered(aa);
console.log(aa);
};
return (
<div>
<select id="select" onChange={handle}>
<option value="0">--choose an option--</option>
<option value="10">0-10</option>
<option value="20">11-20</option>
<option value="21">≥21</option>
</select>
</div>
);
};
CodePudding user response:
You are comparing using ===
this also checks types and the event is most likelly returning a String
from e.target.value
.
If you are expecting e.target.value
to be a Number
you could parse it before the filter action.
(I get rid of the ternary because is harder to read.)
const aa = newId.filter((item) => {
const value = e.target.value; // Now its a number
if (value === 0) return true; // will filter all
if (value === 21) return item.id >= 21 //only true if the item is equal or higher than 21
// Basically any other case
return item.id <= value && item.id > value - 10
});
CodePudding user response:
You have the type if id as integer on your array of objects but you set value as string and again you compare string with integer. Thats why this problem occured.
Please look through this example:
const App = () => {
const data = [
{
date: '2005',
id: 27,
},
{
date: '2005',
id: 27,
},
{
date: '2003',
id: 3,
},
{
date: '2001',
id: 19,
},
{
date: '2000',
id: 4,
},
{
date: '2014',
id: 30,
},
{
date: '2011',
id: 16,
},
{
date: '2011',
id: 10,
},
{
date: '2011',
id: 20,
},
{
date: '2011',
id: 21,
},
];
const [newId, setNewId] = useState(data);
const [filter, setFiltered] = useState();
const handle = (e) => {
const aa = newId.filter((item) =>
Number(e.target.value) === 0
? item.id > 0 //return all id, doesn't work
: Number(e.target.value) === 21
? item.id >= 21 //return id >= 21, doesn't work
: item.id <= Number(e.target.value) && item.id > Number(e.target.value) - 10
);
setFiltered(aa);
console.log(aa);
};
return (
<div>
<select id="select" onChange={handle}>
<option value={0}>--choose an option--</option>
<option value={10}>0-10</option>
<option value={20}>11-20</option>
<option value={21}>≥21</option>
</select>
</div>
);
};
export { App }