0

I am trying to set the local state from a prop, like this:

constructor() {
    super();
    this.toggleDetails = this.toggleDetails.bind(this);
    this.resetFields = this.resetFields.bind(this);

    this.state = {
      showDetails: [],
      result: this.props.simulationResult.simulationResult,
    };
  }

And then pass it later in the render method to child components like this:

const { showDetails, result } = this.state;

<Table
   showDetails={showDetails}
   toggleDetails={this.toggleDetails}
   result={result}
/>

I am receiving this prop with an api call in the mapStateToPros method like this:

simulationResult: getSimulationResult(state),

I am not sure why do I get undefined, and how can I fix this so that I a can set the state in the class with the props?

Leff
  • 1,968
  • 24
  • 97
  • 201
  • Why do you need to store it in state? Why not just pass it down to `Table` directly from the prop? Do you change its value anywhere in this component? – bamtheboozle Dec 07 '18 at 12:47
  • I will be changing the value, since simulationResult is the object with two properties and I will be toggling between them later. – Leff Dec 07 '18 at 12:50
  • 2
    This is why it's generally a bad idea to set state from props (see https://reactjs.org/docs/react-component.html#constructor, yellow box a bit further down). The constructor is called only once, when the props change they're not automatically copied to the state again. – JJJ Dec 07 '18 at 12:50
  • 1
    ...also `this.props` are undefined in `constructor` until you set them through `super(props);` call. So make constructor to be `constructor(props) { ...` and pass `props` into `super()`. Or you can just use `props` in constructor instead of `this.props` – skyboyer Dec 07 '18 at 12:53
  • @JJJ So, how can I achieve this then, to toggle between two properties of an object recevied from the props? – Leff Dec 07 '18 at 12:53
  • Possible duplicate of [What's the difference between "super()" and "super(props)" in React when using es6 classes?](https://stackoverflow.com/questions/30571875/whats-the-difference-between-super-and-superprops-in-react-when-using-e) – skyboyer Dec 07 '18 at 12:54
  • You make it the parent component's responsibility to pass the correct data instead of the entire thing, and then just use that directly. So `result={showDetails ? result.whatever : result.somethingelse}` for example in the parent component. – JJJ Dec 07 '18 at 12:57
  • This is the parent component, but I guess I can set the default option in the state, and use the properties based on that value without copying the prop to state directly. – Leff Dec 07 '18 at 13:07

0 Answers0