Arvind yadav
Arvind yadav

Reputation: 105

state is updated but not getting in other handler in ReactJs

There is two handler copy Handler and paste Handler, in copy Handler i want to change the copy state with props and want to console copy.

I tried but in console i am getting null not updated value of copy.

Here is my code i have tried.In my project i am tring to copy one card Id and pass to other card. Here in above example i am getting the updated value in the console but i my project i am using the same thing. In my project there are some cards i am getting from my an array. On clicking one card i want to get the clicked card id and pass to other card.

So please help me to fix this issue.

import React, { Component } from "react";

class Dummy extends Component {
  constructor(props) {
    super(props);
    this.state = {
      copy: null
    };
  }

  copyHandler = () => {
    this.setState({ copy: this.props.mname });
    // updating the props
  };
  pasteHandler = () => {
    console.log(this.state.copy);
    // getting null
  };

  render() {
    return (
      <div>
        <button className="btn" onClick={this.copyHandler}>
          {" "}
          copy
        </button>
        <button className="btn" onClick={this.pasteHandler}>
          {" "}
          paste
        </button>
      </div>
    );
  }
}

export default Dummy;

Here in above example i am getting the updated value in the console but i my project i am using the same thing. In my project there are some cards i am getting from my an array. On clicking one card i want to get the clicked card id and pass to other card.

So please help me to fix this issue.

Upvotes: 1

Views: 33

Answers (1)

Kishor
Kishor

Reputation: 2677

Sometimes the state and props values are not up to date values while setting a state. You have to use another version of setState.

this.setState((prevState, props) => {
    const newState = { ...prevState, copy: props.mname };
    return newState;
});

Upvotes: 1

Related Questions