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

How can I update individual elements of an array using state hook?

This is the section of code I am dealing with,

This is my hook

const [array, setArray] = useState(
    JSON.parse(localStorage.getItem("notes")) ?? []
  );

And this is the function,

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

  const save = () => {
    let info = one.current.value;
    console.log(newIndex, " and ", info);
    console.log("this si array element -> ", array[newIndex - 1]);
    array[newIndex - 1] = info;
    if (newIndex !== undefined) {
      setArray((e) => {
        return e.map((e1, i) => {
          if (i + 1 === newIndex) {
            return [...e ];
          }
        });
      });
    }
  };

info has the correct input I want to update to and newIndex have the index of the element I wish to update.

Can you suggest to me what I need to change in this section, this is part of the above function,

setArray((e) => {
        return e.map((e1, i) => {
          if (i + 1 === newIndex) {
            return [...e ];
          }
        });

Code Sand box link here

https://codesandbox.io/s/silly-neumann-b0foos?file=/src/styles.css

>Solution :

To update your array you do not need to map anything. You only need to copy the array, modify the copied array at the right index and return the copied array. React will take care of the rest.

It’s important, that you copy the array, else react won’t notice the change. useState only remembers the array’s address in memory.. Only through a new array with a new address will useState actually fire.

Here is my take on what I think your save() function should look like:

const save = () => {
let info = one.current.value;
if (newIndex !== undefined) {
  console.log(newIndex, " and ", info);
  console.log("this is array element -> ", array[newIndex - 1]);
  setArray((e) => {
    let temp = [...e];
    temp[newIndex - 1] = info;
    return temp;
  });
}
};

Tried the code in codesandbox and I think this is what you want.

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