Matteo Fioroni
Matteo Fioroni

Reputation: 103

React typescript counter doesn't update

I wrote my first component in react with typescript: a simple counter.

The tree is : Index -> App (react/js) -> counter (react/js).

Cliking the buttons the state.count is incremented/decremented. I see with the console.log, but the tag with {state.count} isn't updated on click?

Why? Where is my mistake?

Thank you for your help.

I tried to add key property to div tag.

Counter.tsx

import React from "react";

interface IState {
  count: number;
}



export default function Counter(): JSX.Element {

const state: IState = { count: 0 };

const increment = (): any => {
  console.log(state);
     state.count= state.count + 1

};

const decrement = (): any => {
  console.log(state);

  state.count = state.count - 1;
};
  return (
    <div>
      <h2>Counter</h2>
      <div>
        <button onClick={decrement}>-</button>
        <div key={state.count}>{state.count}</div>
        <button onClick={increment}>+</button>
      </div>
    </div>
  );
}

App.tsx

import React from 'react'
import Counter from "./counter";

export default function App():JSX.Element {
    return (
      <div>
        <Counter />
      </div>
    );
}

index.tsx

import React from 'react'
import ReactDOM from "react-dom";
import App from './components/App'

const root = document.getElementById('app-root')
ReactDOM.render(<App />, root);

I expect that by clicking the buttons the number changes.

Upvotes: 1

Views: 2902

Answers (2)

Matteo Fioroni
Matteo Fioroni

Reputation: 103

Here the code solve the problem:

import React,{useState} from "react";

interface IState {
  count: number;
}



export default function Counter(): JSX.Element {
 const [count, setCounter] = useState(0);
const state: IState = { count: 0 };

const increment = (): any => {
  console.log(state);
     setCounter(count+1);


};

const decrement = (): any => {
  console.log(state);
  setCounter(count -1);

};
  return (
    <div>
      <h2>Counter</h2>
      <div>
        <button onClick={decrement}>-</button>
        <div key={count}>{count}</div>
        <button onClick={increment}>+</button>
      </div>
    </div>
  );
}

Upvotes: 0

Dupocas
Dupocas

Reputation: 21317

You are mutating the state!! Try this:

this.setState({count : this.state.count + 1})

Upvotes: 4

Related Questions