ReactJS: Reload component if variable changes value
Solution 1
Try moving the user declaration into state. That way, when Meteor.user() updates, it will update state and trigger a re-render.
class App extends Component {
constructor(){
super();
this.state = {
user: Meteor.user()
}
}
render () {
const { user } = this.state;
if (user && user.check) {
return (<AnotherComponent />)
}
return (<MainComponent />)
}
}
Solution 2
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>
user3142695
People who say nothing is impossible should try gargling with their mouths closed.
Updated on June 18, 2022Comments
-
user3142695 almost 2 years
In my main component
<App />
of my meteorJS application I'm using some user data (const user = Meteor.user()
). If theuser
-object has acheck
value<AnotherComponent />
will be used. There the user can do some interaction and thecheck
field gets removed fromuser
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 />) } }