Update component state from outside React (on server response)

Can you trigger a component state change outside a component?

Yes. Heres a simple example

In your react component set up a globally available closure which will update it’s state when the function is fired.

componentDidMount(){
 globalVar.callback = (data) => {
    // `this` refers to our react component
    this.setState({...});     
  };
}

Then when your ajax’d response comes back you can fire the event with the returned data

globalVar.callback(data);

Or for something more robust, use a custom event or subscription

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)