-1

I have a function which I am trying to change the properties of an object inside an array of objects at a particular index:

const handleEdit= (index) =>{
 if(itemList[index].edit==true){
  const copied=[...itemList];
  const item2 = {...itemList[1]};
  item2.edit= true;
  item2.Name='test';
  copied[index]=item2;
  setItemList(copied);
  console.log("correct",itemList);
} 

When I look at the log, the "Name" property properly updates from it's previous value to "test" but the boolean "edit" property stays at it's previous value. What am I doing wrong here?

haredev
  • 67
  • 1
  • 10
  • 1
    It's difficult to understand what's happening here. You check for edit==true, copy item [1], set edit=true. Not sure how we're supposed to think about this. – Dave Newton Aug 14 '21 at 19:41
  • 1
    Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – Rafael Tavares Aug 14 '21 at 20:01
  • Yes thanks edemain et. al – haredev Aug 14 '21 at 20:09

1 Answers1

1

Your code looks correct, except for the console.log statement. You shouldn't expect itemList (or state in general) to update immediately when you call a state setter like setItemList. Setting state schedules a future update.

If you instead console.log(itemList) e.g. immediately after itemList's declaration, you should see it updated.

edemaine
  • 2,699
  • 11
  • 20
  • As @DaveNewton wrote above, your code checks for `edit === true`, and in that case, sets `edit` to `true`. That's not going to change the `edit` property... – edemaine Aug 14 '21 at 19:53