0

i want to parse data from child to parent i have try solution from question

How to parse data from child to parent using reactjs?

I print that state and what appears is the state of the previous action, not the state of the last action

I tried to implement this to bring up content based on the menu that was clicked example: i have 3 menu - A - B - C

when i click first time at the menu, for example A. the state in console is '', Then Second time i click B, the state in console is A

this is my code

PARENT

changeMenu= (menu) =>{
    this.setState({
        menu: menu
    });
    console.log('menu',menu);  // Show State
}

render(){
    return (
        <LeftMenuMycommission active="0" menu = {(value) => this.changeMenu(value)}/>

CHILD

menuClick = (menu_name, active) =>{
    this.setState({
        menu: menu_name,
    })
    this.props.menu(this.state.menu); 

}

render (){
    render (
        <ul>
            <li ><a onClick={this.menuClick.bind(this, "A")}><i className={"fa fa-circle"}></i> A</a></li>
            <li ><a onClick={this.menuClick.bind(this, "B")}><i className={"fa fa-circle"}></i> B</a></li>
            <li ><a onClick={this.menuClick.bind(this, "C")}><i className={"fa fa-circle"}></i> C</a></li>
        </ul>

Can anyone help me to find the problem?

Any help would be appreciated thank you :)

Nur Diarto
  • 55
  • 2
  • 10
  • This question came up many times.. So I think someone will def link it to those already asked questions.. :) – Arup Rakshit Aug 22 '18 at 11:26
  • thank you sir, I have read the same question that appeared when filling the title of the question, and I have tried it, but it has it as I explained :) – Nur Diarto Aug 22 '18 at 11:34

1 Answers1

1

It's not guaranteed that state is updated immediately. You would need to use callback function and then call your parent method to pass the child component state to the parent correctly:

menuClick = (menu_name, active) =>{
    this.setState({
        menu: menu_name,
    }, () => {
     this.props.menu(this.state.menu); 
    })
}

Or, componentDidUpdate will do the same job:

componentDidUpdate() {
  this.props.menu(this.state.menu) // only called after component is updated
}
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
  • thanks for your help, i have tried for number 1 solution the state is undefine in the console, and for the second solution the state is printed continuously when i open the page – Nur Diarto Aug 22 '18 at 11:54