How to change some attributes of an object with Hooks

Asked

Viewed 43 times

-1

I want to update only some attributes of an object, these attributes are varied, one time I want to update some, another time. Follow the example:

const [myObject, setMyObject] = useState({
 apartments: 0,
 hoods: 0,
 elevators: 0,         
 heating: 0,
 })

So suppose I have the following other state:

let novaAtualizacao = [{ elevators: 5, heating: 1}]

That’s what I want myObject update only what is on novaAtualizacao. I tried so:

setMyObject(prevState => {
            return { ...prevState, novaAtualizacao }
           });        

But it didn’t happen. Someone can help me?

  • novaAtualizacao is an array, so Voce should select the first element and then perform the de-structuring. Something like: return { ...prevState, ...novaAtualizacao[0] }, values will be updated according to the values in novaAtualizacao. Another thing, if Voce will adjust a new state, use setMyObject and not myObject.

  • I did the de-structuring but is only taking the first element of newupgrade, being that I need all that are inside it

1 answer

1


Need to do a breakdown of the current value and as the given example is a array of object with a position it is necessary to position in that position and also to do the destructuring (...novaAtualizacao[0]) for the change of state, example:

let novaAtualizacao = [{ elevators: 5, heating: 1}];
setMyObject(state => {
    return { ...state, ...novaAtualizacao[0] };
});

Full example:

function App() {
  const [myObject, setMyObject] = React.useState({
    apartments: 0,
    hoods: 0,
    elevators: 0,         
    heating: 0,
  })
  function handleClickAlterar(e) {
    let novaAtualizacao = [{ elevators: 5, heating: 1}];
    setMyObject(state => {
      return { ...state, ...novaAtualizacao[0] };
    });
  }
  return (
    <div>
      <div>
        {JSON.stringify(myObject)}
      </div>
      <div>
        <button onClick={handleClickAlterar}>Alterar</button>
      </div>
    </div>
  )
}
ReactDOM.render( <App/> , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root">Carregando ...</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.