Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading