'Instead of adding value i'm replacing the value of array
Hi all i'm trying to get an array of Sizes and Color which is inside an object. So when we click on the input a handler will be call i.e., clickHandler() but the code when run it replacing the value of the array each time when the handler is invoked.
export default function MiniDrawer() {
const [open, setOpen] = React.useState(true);
const [attributes, setAttributes] = React.useState([]);
const [filterArray, setFilterArray] = React.useState({
Size: [],
Color: []
});
const clickHandler = (n, v) => {
setFilterArray({...filterArray, [n]:v})
}
React.useEffect(() => {
axios.get('http://localhost:3004/attributes')
.then(res => setAttributes(res.data))
.catch(e => console.log(e))
},[])
return (
<Box sx={{ display: 'flex' }}>
<CssBaseline />
<AppBar position="fixed" open={open}>
<Toolbar>
<Typography variant="h6" noWrap component="div">
Dynamic Filter
</Typography>
</Toolbar>
</AppBar>
<Drawer variant="permanent" open={open}>
<div className='text-left'>
<Typography variant='h6' className='m-2'>
Filters
</Typography>
</div>
<Divider />
<div className="list-conntainer" style={{paddingLeft: '25px'}}>
<List>
{
attributes.length > 0 && attributes.map((attribute, index) => {
return (
<div className='mb-5' key={index}>
<h4>{attribute.att_id}</h4>
{
attribute.att_value.map((v, index) => {
return (
<div className="form-check mb-1">
<input className="form-check-input" onClick={() => clickHandler(attribute.att_id, v)} type="checkbox" />
<label className="form-check-label" htmlFor="flexCheckDefault">{v}</label>
</div>
)}
)
}
</div>
)
})
}
</List>
</div>
</Drawer>
<Box component="main" sx={{ flexGrow: 1, p: 3 }}>
<DrawerHeader />
<CardContainer filterArray={filterArray} />
</Box>
</Box>
);
}
Inside the handler i'm passing two arguments which are key and value. The key can be either Size or Color.
let me also share the json folder.
"attributes": [
{
"att_id": "Size",
"att_value":[ "S", "M", "2XL", "L", "XL", "XS", "3XL" ]
},
{
"att_id": "Color",
"att_value": ["Red", "Blue", "Silver", "Green", "Yellow", "Black"]
}
My desire output is: { Size: [S, M, L], Color: [Red, Blue] }.
But Actual Output which i getting is : { Size: M, Color: Red }.
Solution 1:[1]
I think the issue here is both syntaxic and logical. syntaxic because in your click handler you are replacing the array by a single value indeed. This can be changed like this:
const clickHandler = (name, value) => {
let newArr = filterArray[name];
if (!newArr.includes(value)){
newArr.push(value)
} else {
//remove value from array
}
setFilterArray(...filterArray, [name]: newArr);
}
I think in your case having arrays of booleans for the filterArray would make more sense and be more efficient.
Hope this helps.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sophia Koulen |
