Search code examples
javascriptreactjswebsocketreact-d3

React js update child state from an event in the parent


I have a WebSocket that's feeding data to the client and, i'm displaying it (data) in a chart using D3 in react, and so i want my chart to change according to the data, but to change the state of the chart component, i have to access it from the parent component where the onMessage event is defined, my problem is that the chart doesn't update :

Parent Component :

class App extends Component {
constructor(props) {
    super(props);
    this.state = {
      data: [],
    };
  }
  handleData(data) {
      let result = JSON.parse(data);
      this.setState((state) => {
        state.data.push(result.c.gas);
      });
  }

  render() {
    return (
      <div>
        <Websocket
          url={`ws://${window.location.host}/ws/mqtt_app/1/`}
          onMessage={this.handleData.bind(this)}
        />
        <Chart data={this.state.data} />
      </div>
    );
  }
}

Child component :

const Chart = (props) => {
  const [data, setData] = useState(props.data);
  const svgRef = useRef();

  useEffect(() => {
    // chart definition
  }, [data]);

  return (
    <React.Fragment>
      <svg ref={svgRef}>
        <g className="x-axis"></g>
        <g className="y-axis"></g>
      </svg>
    </React.Fragment>
  );
};

export default Chart;

Thank you


Solution

  • You need to assign a new value to the state variable. Please try this

    this.setState(state => ({ data: [...state.data, result.c.gas] }))
    

    In your case you were mutating its value