Placing items in an array with Reactjs

Asked

Viewed 302 times

0

inserir a descrição da imagem aqui

I’m trying to put items in a array by clicking the button, but the same one is starting empty. Notice that I clicked 3 times but it shows me that the array has 2 positions.

I have a div which is the display that one div receives the state of the constant operation which is an array. Clicking on a button triggers a function called addOperation(2) with the value 2, which places this number inside the array.I am using setOperation([...operation, value]) to push the number on array.

The problem is that by clicking the button the program puts the number in the second position of the array, and the first one is empty, you know what may be happening?

  • 1

    The state update is an asynchronous operation. One of the ways to get the updated value is to use useEffect. Here are some examples: https://reactjs.org/docs/hooks-effect.html

  • 1

    An important thing, do not put the image, only in certain case, for example that is code, always put the code.

  • One thing if my answer was the solution of your problem accepted as answer and take a look at the tour so you know how it works.

1 answer

1

What’s going on is that your array is being updated right with the 3 positions created, but, does not show this in the console.log because the ReactJs did not update your component, for this to happen you need to use the useEffect that at the time of variable update the value of the new array is shown, example:

function App() {
  const [operation, setOperation] = React.useState([]);
  React.useEffect(() => {
    console.log(operation);
  }, [operation]);
  function addOperation(value) {
      setOperation([...operation, value]);
  }
  return (
    <div>
      <button onClick={e => addOperation(2)}>Add</button>
      <ul>
        {operation.map((o,i)=>(<li key={i}>{o}</li>))}
      </ul>      
    </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"></div>

the useEffect in this case it is observing the changes in the variable and this shows the correct value of the positions according to the update of the component because the state is always asynchronous.

Browser other questions tagged

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