Issues with useState in react

Okay, I have a useState object in react that I’m trying to update and it only works as detaild below. There’s the initial object and I have an object from the server that has null and non-null fields. I want to update only the non-null fields on the initial object. The view doesn’t re-render when trying to update the initial object. The following works, but I can’t leave out the null fields:

[test, setTest] = useState();
let data = client.update();

setTest(test => {
 return {...test, area: data.area}; 
});

This doesn’t work:

setTest(test => {
  let update = test;
  if(data.area !== null){
    update.area = data.area;
  }
 /// doesn't work
 return update;
})

This doesn’t work either:

setTest(test => {
  let update = test;
  if(data.area !== null){
    update.area = data.area;
  }
  // doesn't work
  return Object.assign(test, update);
}); 

Your use of Object.assign is not quite right. You are taking two equivalent references to the same object, and then assigning the props from one to the other, which would do nothing. JS assigns most objects by reference, not copy. You’ll probably want to do something like this:

setTest(test => {
  // make a copy
  let update = Object.assign({}, test);
  if(data.area !== null){
    // assign area to copy
    update.area = data.area;
  }
  return update;
}); 

That works, thank you. I thought that test was being copied to update.

I don’t think the callback form is necessary in this case:

let data = client.update();
[test, setTest] = useState({});
if (data.area !== null) setTest({...test, area: data.area})