Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS: Reload component if variable changes value

In my main component <App /> of my meteorJS application I'm using some user data (const user = Meteor.user()). If the user-object has a check value <AnotherComponent /> will be used. There the user can do some interaction and the check field gets removed from user document.

To make it a bit clearer: The check value will be removed on another place by updating the value in the db.

Now I would expect, that now <MainComponent /> will be rendered. But it won't. I need to reload the page to get it.

Is there a way how I can make the user variable 'reactive'?

class App extends Component {
  render () {
    const user = Meteor.user()

    if (user && user.check) {
      return (<AnotherComponent />)
    }
    return (<MainComponent />)
  }
}
like image 873
user3142695 Avatar asked Aug 10 '17 20:08

user3142695


1 Answers

if you want to reload a render, your component has need a variable in a state that can be change. Or receive some new props.

In your case, this is normal you've to reload the page.

if you want to run render() in App component, you need to store the user in a state, and find a way to call Meteor.user again to retrieve some new data and replace in the user state. If the state.user has changed, then, your component will be rerendering.

class App extends Component {
  constructor() {
    super();
    this.state = {
      user: Meteor.user(),
    }
    this.smthChanging = this.smthChanging.bind(this);
  }
  
  smthChanging() {
    this.setState({
      user: Meteor.user(),
    });
  }
  
  render () {
    const { user } = this.state;

    if (user && user.check) {
      return (<AnotherComponent />)
    }
    return (
      <div>
        <button
         onClick={this.smthChanging}
        >
          reload user
        </button>
      </div>
    )
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
like image 185
Jean-louis Gouwy Avatar answered Oct 15 '22 11:10

Jean-louis Gouwy