how to make my function return increment?

Asked

Viewed 36 times

0

is the following I’m having a hard time finding where is the error of this code, I want to make a counter, but every time is saying that setCounter is not a function.

import React, {useState}from 'react';
//componente: e um bloco isolado de HTML, CSS e JS, o qual não interfere no resto da aplicação
// propriedade: informaçoes que um componete PAI passa para um componente filho.
// Estado:



//pro exemplo o app e um componente 
function App() {
  //bom aqui foi criado uma variavel counter que vai pegar o useState que vai comecar com o valor 0.
  const {counter, setCounter} = useState(0);
  function incrementCounter(){
      setCounter(counter + 1);
      }
  return(
    <>
      <h1>Contador: {counter}</h1>
      <button onClick={incrementCounter}>incrementar</button>
    </>
  )

}

export default App;

help me Please!

  • If this answer solved your problem and there is no doubt left, mark it as correct/accepted by clicking on the " " that is next to it, which also marks your question as solved. If you still have any questions or would like further clarification, feel free to comment.

1 answer

2

You are using the wrong destructor. Keys {} are used to unstructure an object, brackets [] server to unstructure an array.

The return of function useState is an array with two items, the first item represents its state, and the second is the method for changing its state. So, to store these two items in variables, you should be using const [counter, setCounter] = useState(0).


Another detail for the code: the function setCounter will not change its status immediately after being invoked, there is no guarantee that the value of counter it will still be the same as it was when you invoked setCounter, which can generate an inconsistency. When you need to change your state based on a previous value, you should use callbacks instead of

setCounter(counter + 1)

Utilize

setCounter(counter => counter + 1)

Browser other questions tagged

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