Change object`s value in useState

I have array with objects like [{id: 123, isTrue: true}]. The array I get with props in my component. And in it I have to change isTrue when my component mount. I use useState and useEffect:

  const [myArray, setMyArray] = useState([]);
  useEffect(() => {
    setMyArray(arrFromProps.map((item) => {
      item.isTrue = false;
    }));
  }, []);

And nothing. I can not get in my objects changed value. Cuold you explain me why? Thanks in advance!

>Solution :

The issue with your code is that you are not returning the modified array in the map(). The map() function creates a new array with the same length as the input array by applying the provided function to each element of the input array. However, your map() function is not returning the modified element, it’s just changing the isTrue property of the original element.

you should modify the map() function to return a new object with the updated isTrue property like this.

const [myArray, setMyArray] = useState([]);
useEffect(() => {
  setMyArray(arrFromProps.map((item) => {
    return { ...item, isTrue: false };
  }));
}, []);

In the map() function, we are creating a new object with the spread operator ({…item}) to copy all properties of the original object, and then we are setting the isTrue property to false. This will create a new array with the modified objects, and the state will be updated accordingly.

Leave a Reply