onedkr
onedkr

Reputation: 3386

Refresh react component

My node.js server sends with socket.io new data each 10s. In my web application I update this.state each time that my server sends data and force to update with forceUpdate()

However, my react component doesn't refresh, I don't know why. I followed the doc but I missed something...

Parent :

class DataAnalytics extends React.Component {
  constructor(props) {
    super(props);
    socket = this.props.socket;
    this.state = {data: []};

    socket.on('dataCharts', (res) => {
      console.log("new data charts : "+res);
      var data = JSON.parse(res);   
      this.setState({data: data});
      this.forceUpdate();
    });
  }

  componentWillUnmount() {
    socket.off('dataCharts');
  }

  render() {
    return (
    <div id="dataAnalytics">
      <Stats data={this.state.data}></Stats>
    </div>
    );
  }
}

export default DataAnalytics;

Child :

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

  render() {
    return (
      <div className="stats" style={{textAlign:'center'}}>
        <h4>Number: </h4>
      </div>
    );
  }

  componentDidUpdate() {
    var data = this.props.data;

    if(!jQuery.isEmptyObject(data)) {
      $( ".stats" ).html("<h4>Number : data['nb']['counterIn']</h4>");
    }
  }
}

export default Stats;

Anyone know how to refresh automatically my React component.

Upvotes: 1

Views: 5657

Answers (2)

roshnet
roshnet

Reputation: 2073

I usually do it like -

function MyComponent() {
  const [_, refresh] = useState()

  useEffect(() => {
    // Code that's supposed to run on refresh
  }, [refresh])

  return 
    <>
      {/* Rest of the code */}
      <button onclick={() => refresh(true)}>Refresh</button>
    </>

}

The idea is to define a state and use it as a dependency of useEffects (or useMemos and useCallbacks).

If there are multiple effect hooks, add refresh to all of them as a dependency.

Upvotes: 0

Raul Rene
Raul Rene

Reputation: 10270

The React component doesn't update because it doesn't realize that it's state changes. You can force an update on a React component by creating it each time with a different key attribute.

render() {
     return (
         <div id="dataAnalytics">
             <Stats key={this.uniqueId()} data={this.state.data}></Stats>
         </div>
    );
}

// Example of a function that generates a unique ID each time
uniqueId: function () {
    return new Date().getTime();
}

Upvotes: 4

Related Questions