mit katwala
mit katwala

Reputation: 109

State doesn't get set with this.setstate in React form

I am building a form in React. On clicking cancel the form in App component needs to reset the state which I am getting from another component Data

class App extends React.Component {

constructor(props){
  super(props);
  this.Data = React.createRef();
  this.state = {
    fruits:["Mango","Apple","Banana"],
  };
}

//reset method in App called on clicking cancel in form
resetForm(e){
  e.preventDefault();
  const resetState = this.Data.current.getFruit();
  console.log(resetState);
  this.setState({
    state: resetState
  });
}

//class in different file
export class Data extends React.Component {
  getFruit() {
    return {    
      fruits: [
        "Mango",
        "Apple",
        "Bananna"
      ]
    }
    //more code below
}

When I console resetState in resetForm method I am able get the initial states from Data component but it doesn't set it to the state in App. What am I doing wrong? I am new to React

Upvotes: 1

Views: 45

Answers (1)

losik123
losik123

Reputation: 590

When you use the setState method React already knows it should be applied to the state property, so you should be calling the method with:

this.setState(resetState);

Upvotes: 2

Related Questions