this.setState not working when a parent's state has to be updated by a child

Viewed 1216

So I have a parent and a child component in my app. I want to update the state of the parent component by the child component but it doesn't seem to work. I have been working on Reactjs for a long time now and this is quite strange to me. Here is my code for the parent component:

import React from 'react';
import { Stage } from 'react-konva';
import CircleComponent from './CircleComponent';
import LineComponent from './LineComponent';
import { getUserPlan } from '../../assets/UserPlan';
import { addColorClasses } from '../../helpers/utils';

class PortfolioMix extends React.Component {
  constructor(props) {
    super(props);

    const data = addColorClasses(getUserPlan().plans[0]);

    this.state = {
      data: data,
      circlePoints: []
    };

    this.getCirclePoints = this.getCirclePoints.bind(this);
  }

  getCirclePoints(points) {
    this.setState({
      circlePoints: points,
      word: 'hello'
    }, () => { console.log(this.state); });
  }

  processData() {
    let data = this.state.data;

    if(data[0].weight > 0.25 || (data[0].weight+data[1].weight) > 0.67) {
      for(let i = 0; i < data.length; i++) {
        data[i].weight /= 3;
      }
    }

    return data;
  }

  render() {
    const processedData = this.processData();
    const firstCircle = processedData.splice(0,1);
    const pmData = processedData.splice(0,this.state.data.length);

    return(
      <div>
        <Stage
          height={800}
          width={1200}
          style={{ backgroundColor: '#fff'}}>
          <CircleComponent
            x={1200/2}
            y={800/2}
            outerRadius={firstCircle[0].weight*1200}
            outerColor={firstCircle[0].outerColor}
            innerRadius={firstCircle[0].weight*1200*0.3}
            innerColor={firstCircle[0].innerColor}
            shadowColor={firstCircle[0].innerColor}
            getCirclePoints={this.getCirclePoints}
          />
        </Stage>
      </div>
    );
  }
}

export default PortfolioMix;

And here is the child component's code:

class CircleComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      points: this.getPoints(),
    };
  }

  componentDidMount() {
    this.props.getCirclePoints(this.state.points);
  }

  getPoints() {
    const radius = this.props.outerRadius;
    const x = this.props.x;
    const y = this.props.y;

    const points = [];
    let angle = 0;

    for(let i = 0; i < 8; i++) {
      points.push({
        pointX: x + radius * Math.cos(-angle * Math.PI / 180),
        pointY: y + radius * Math.sin(-angle * Math.PI / 180)
      });
      angle += 42.5;
    }

    return points;
  }

  render() {
    const {
      x,
      y,
      outerRadius,
      outerColor,
      shadowColor,
      innerRadius,
      innerColor
    } = this.props;

    return (
      <Layer>
        <Group>
          <Circle
            x={x}
            y={y}
            radius={outerRadius}
            fill={outerColor}
            shadowBlur={5}
            shadowColor={shadowColor}
          />
          <Circle
            x={x}
            y={y}
            radius={innerRadius}
            fill={innerColor}
          />
        </Group>
      </Layer>
    );
  }
}

CircleComponent.propTypes = {
  x: propTypes.number.isRequired,
  y: propTypes.number.isRequired,
  outerRadius: propTypes.number.isRequired,
  outerColor: propTypes.string.isRequired,
  shadowColor: propTypes.string,
  innerRadius: propTypes.number.isRequired,
  innerColor: propTypes.string.isRequired,
  getCirclePoints: propTypes.func
};

export default CircleComponent;

Now, in parent component's getCirclePoints method, I am getting the points from the child but this.setState is not working. As you can see I have also passed a function to this.setState callback, it isn't getting called and also setting data state to an empty array. I have been banging my head on this for last 4 hours. Any kind of help is appreciated. I hope there's not some stupid mistake on my side.

2 Answers

In React docs you can read that the state should not be modified directly but only with the setState() method. You did modify PorfolioMix state directly twice:

  1. in processData:

    data[i].weight /= 3;
    
  2. in render:

    const processedData = this.processData();
    const firstCircle = processedData.splice(0,1);
    const pmData = processedData.splice(0,this.state.data.length);
    

Because the render method in your code is called at least twice, this.state.data will be an empty array which leads to an error.

You can see a live example with the error here: https://jsfiddle.net/rhapLetv/

To fix it, you can return a copy of the data in the processData method:

processData() {
  const data = this.state.data;

  if(data[0].weight > 0.25 || (data[0].weight+data[1].weight) > 0.67) {
    return data.map(point => ({ ...point, weight: point.weight / 3 }))
  } else {
    return data.slice()
  }
}

Live example with fixes: https://jsfiddle.net/rhapLetv/1/

You can find useful immutable.js (or similar libraries/helpers) which introduces immutable data.

You need to .bind(this) at method processData() too, because React only automatically bind(this) to render method, constructor and component lifecycles methods.

class PortfolioMix extends React.Component {
  constructor(props) {
    super(props);

    const data = addColorClasses(getUserPlan().plans[0]);

    this.state = {
      data: data,
      circlePoints: []
    };

    this.getCirclePoints = this.getCirclePoints.bind(this);
    this.processData = this.processData.bind(this);
  }
// ...
Related