'How to dynamically change object values of a state after a callback in React?

Rookie question. Consider the code snippet below for a second:

export const Parent = ({data}) => {
  const [myData, setShowResults] = useState({isOpen: false, title: 'test'})

  function handleCheck(evt) {
      console.log(evt.currentTarget.textContent);
      //how to change current myData.title with evt.currentTarget.textContent?

  }
  return (
    <div className='c-dropdown'>
        <Child data={data} isOpen={myData.isOpen} onCheck={handleCheck}/>
        <p>{myData.title}</p>
    </div>
  );
}

Inside the handleCheck callback function I receive the desired information, yet I cannot find a way how to change myData.title with the newly received information.



Solution 1:[1]

Use a functional state update and shallow copy the previous state object.

Example:

function handleCheck(evt) {
  const { textContent } = evt.currentTarget;
  console.log(textContent);
  setShowResults(data => ({
    ...data,            // <-- copy previous state
    title: textContent, // <-- update property
  }));
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1