0

I'm practice send state to Child-component - Parent-Component - Another-Child-Component.

and I was stuck on my practice,

First, I was successful to make react counter like this child component

Second, I want to send counter value to another component. I know how to send state to another child component. But i stuck my work.

Send state to another component

when i first clicked + button, it works only First child. and then, when i clicked once more, it works another child too(not match number)

How can I dealing this problem?

This is my code.


// This is Counter.js

class Counter extends Component {
    state = {
        counter: 0
    }

    handleIncrement = () => {
        this.setState(({ counter }) => ({
            counter: counter + 1
        }))
        this.props.handleCounter(this.state.counter)
    }

    handleDecrement = () => {
        this.setState(({counter}) => ({
            counter: counter - 1
        }))
        this.props.handleCounter(this.state.counter)
    }

    render() {
        return (
            <div>
                <h1>Counter</h1>
                <h3>{this.state.counter}</h3>
                <button onClick={this.handleIncrement}>+</button>
                <button onClick={this.handleDecrement}>-</button>
            </div>
        )
    }
}

// This is App.js file

import Counter from './components/counter';
import Sent from './components/sent'

class App extends React.Component {

  state = {
    counter: this.handleCounter
  }

  handleCounter = (counter) => {
    console.log("Received Count 1 ")
    this.setState({
      counter: counter
    })
  }

  render() {
    return (
      <div className="App">
        <Counter handleCounter={this.handleCounter} />
        <Sent result={this.state.counter} />
      </div>
    );
  }

}
// This is Sent.js file 
import React, { Component } from 'react'

class Sent extends React.Component {

    render() {
        return (
            <div>
                <h2>Result ==> {this.props.result}</h2>
            </div>
        )
    }
}
Pete Lee
  • 23
  • 3
  • `setState()` is async. Your operations such as `this.props.handleCounter(this.state.counter)` that occur outside of a `setState()` callback will likely have old values for state. – Alexander Staroselsky Feb 14 '20 at 17:23
  • Does this answer your question? [setState doesn't update the state immediately](https://stackoverflow.com/questions/41278385/setstate-doesnt-update-the-state-immediately) – Alexander Staroselsky Feb 14 '20 at 17:31

0 Answers0