1

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.

3
  • this.setState() might help you Commented Mar 30, 2016 at 14:14
  • I have this.setState() in my parent component... I tried to place it in different method (componentDidUpdate, componentWillMount ...), but same result :/ Commented Mar 30, 2016 at 14:17
  • Your setup inside parent looks correct: data should be new on every cycle, and setState() should re-render parent +child, without even need for forceUpdate(). Are you sure the socket works properly? Do you get multiple console.log lines? Commented Mar 30, 2016 at 20:39

2 Answers 2

4

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();
}
Sign up to request clarification or add additional context in comments.

5 Comments

that isn't correct answer, you can trigger setState event if you dont change your state fiddle and it will re-render compoenent
@The: you are correct. But I'm thinking that he wants it to respond when data changes, without having to manually trigger setState. I was expecting React to work like that also, but I was having sub-components that didn't update because their state was not really updating. So I'm using on some of my components this "trick" with the key attribute
Thank you for your answer :) But I need more precision. How to use correctly this uniqueId on my child component ? For the moment with this unique id my method componentDidUpdate() is not called :/ so any informations are displayed.
@RaulRene i see, i havent faced with something similar
The trick with unique IDs in keys is only relevant if you have a list of children, and some children do not rerender properly. (I would advise a more proper and efficient key though). OP's issue is unrelated to lists, so I doubt key/ID will fix it.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.