2

I am passing the name and value to handleChange function from child component.

Now I want to set the state to the value that matches the provided name. But I do not know how to set it.

I tried this way(but it gives error - 'this.setState is not a function') :

class ParentComponent extends Component {
constructor(props) {

    super(props);
    this.myRef = React.createRef();
    this.state = {
        loanAmount: 348600.48,
        numberOfYears: 70,
 }
  handleChange(name, value) {  
    this.setState({ name: value },() => {
      this.financeCalcualte();
    });
  }

The code of the child component is:

   onChange = (event) => {   
    const {name, rawValue} = event.target;
    this.props.handleChange(name, rawValue)
   }

What is the correct syntax to set it?

Rachit Gupta
  • 89
  • 1
  • 2
  • 8
  • Could you show us more code ? I'd like to see your whole file in order to know if you're in a `component` or `functional component` – Hurobaki Jan 08 '20 at 13:07
  • you need to bind `this` (the component class instance). Where are you using `handleChange()`? – segFault Jan 08 '20 at 13:07
  • 3
    Does this answer your question? [React this.setState is not a function](https://stackoverflow.com/questions/31045716/react-this-setstate-is-not-a-function) – codeblooded Jan 08 '20 at 13:10
  • @codeblooded yes, this answers my question, thanks a lot – Rachit Gupta Jan 09 '20 at 14:34

3 Answers3

6

In order to use this in a callback function, as told in the comments you have to bind it in the constructor or use an arrow function.

Also, since your name is a variable, you can't update your state like:

this.setState({ name: value }

because this creates a name property in your state, does not update the state variable which has the name as your incoming variable. So, you should use a computed property.

handleChange = (name, value) =>
  this.setState({ [name]: value }, () => this.financeCalcualte());
devserkan
  • 16,870
  • 4
  • 31
  • 47
1

It seems like you are looking for computed property name

handleChange(name, value) {
    this.setState({ [name]: value },() => {
      this.financeCalcualte();
    });
  }
Max
  • 4,473
  • 1
  • 16
  • 18
1

If you have this function in a Class based component then you can update your current function to an arrow function like below.

handleChange = (name, value) => {  
 this.setState({ name: value },() => {
  this.financeCalcualte();
 });
}

The thing is you are accessing this without a context being given.

Another way can be you bind this to the function. Below is the example to do it the other way inside your constructor.

constructor(props) {
 super(props);

 this.handleChange = this.handleChange.bind(this);
 // Other code ....
}

EDIT

Also as mentioned in other answer and comments you have to use computed property name, you can not just use a variable name directly and set it to another variable.

this.setState({[name]:value})

shivamragnar
  • 383
  • 2
  • 10