I have a steate with an array of objects:
const [Value, setValue] = useState([
{ value1: false, value2: false, value3: false },
{ value1: false, value2: false, value3: false },
{ value1: false, value2: false, value3: false }
]);
And using the map method, I render a div for each object:
{Value.map((item, i) => {
return (
<div
key={i}
onClick={() => {
setValue((oldArr) => {
let newArr = [...oldArr];
newArr[i].value3 = true;
return newArr;
});
}}
>
{item.value3 ? 'yes' : 'no'}
</div>
);
})}
And then I click to assign the true to the key value3 of the current object.
But I can’t figure out how I should assign the false to all other keys value3 from other objects on this click. Exactly, I want to click and get true for current key value3 and all other value3 get false.
Help me pls!
>Solution :
For one thing, this is mutating state:
newArr[i].value3 = true;
Definitely don’t do that. We can solve both this and the issue at hand by projecting these array elements into a new array, setting other values to false and the target value to true. For example:
setValue((oldArr) => oldArr.map((a, x) => ({
...a,
value3: x === i ? true : false
}));
What this does is map over the existing array, constructing new objects which contain all properties of the existing objects and a manual value for value3, which is true if the index of the array matches i and false otherwise.