1

I'm trying to make a tapper component where everytime a user clicks on the button the number inside of the component goes up one.

enter image description here

The tapper component gets an initial value from a local json file. When the tapper is pressed however it fired the onClick function but doesn't update the state so the number doesn't go up! I'm new to react so I don't know if I'm approching this problem incorrectly.

My intent in the future is for the button to update the json value so that anyone people who visit the page in the future can hit it and make the number go up.

import React, {Component} from 'react';
import {Icon, Label} from 'semantic-ui-react';
import tapperValue from './tappervalue.json';

    export default class TapperOutput extends Component {

      constructor() {
        super();

        this.state = {
          tapperValue: tapperValue.tapperValue
        }
      }

      handleClick = () => {
        console.log('Before the conversion ' + this.state.tapperValue);
        const taps = this.state.tapperValue + 1;
        this.setState = ({tapperValue: taps});
        console.log('After the conversion ' + this.state.tapperValue);
      }

      render() {

        return (
        <Label onClick={this.handleClick}>
          <Icon name='hand paper'/> {this.state.tapperValue}
        </Label>);
      }
    }
cosmichero2025
  • 1,029
  • 4
  • 14
  • 37

1 Answers1

4

First of all, setState is a function and you don't need an assignment operator with it.

Second: setState is async and hence the update isn't visible immediately, so you need to log the value in setState callback. Check this answer for more details

Third: when you are updating the current state based on the previous one, its better to use the updater function syntax provide by setState. Check this answer on when to use Updater function with setState

Simply write

  handleClick = () => {
    console.log('Before the conversion ' + this.state.tapperValue);
    this.setState(prevState => ({tapperValue: prevState.tapperValue + 1}), () => {
        console.log('After the conversion ' + this.state.tapperValue);
    });

  }
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400