Ankit
Ankit

Reputation: 1362

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,

  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 ];
          }
        });

Upvotes: 3

Views: 87

Answers (1)

Victor Bialek
Victor Bialek

Reputation: 51

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.

Upvotes: 2

Related Questions