score:1

Accepted answer

use the map() method as shown below.

inside the callback function, check if the condition element.id === 3 is true; if it is, return a new object. otherwise, return the current element as it is.

let newstate = arrayoftests.map((element) => {
    if (element.id === 3) {
       return { ...element, description: "new description" };
    }
   
    return element;
});

pass the array returned by the map() method to the state setter function.

this.setstate({ state: newstate });

score:0

this.setstate({
  arrayoftests: arrayoftests.map(item => {
    if (item.id === 3) {
      return {
        ...item,
        description: 'new description'
      }
    }
    return item
  })
})

score:0

const [test, settest] = usestate([
        {
            id: 1,
            name: "test1",
            description: "test description"
        },
        {
            id: 2,
            name: "test2",
            description: "test description"
        },
        {
            id: 3,
            name: "test3",
            description: "test description"
        }
    ]);

    const handleupdate = (index) => {
        const some_array = test;
        var newstate =  some_array[index];
        newstate.description =  "new description";
        some_array[index] = newstate;

        settest(some_array);
        console.log(test);
    }

return(
      {test.length > 0 && test.map((data, index)=>{ return(handleupdate(index)}>{data.description})
       })
}  
)

score:1

setstate((prevstate) => ({
  ...prevstate,
  arrayoftests: prevstate.arrayoftests.map((item) =>
    item.id === 3 ? { ...item, description: "new description" } : item
  ),
}));

Related Query

More Query from same tag