Reputation: 2290
How can I cancel setInterval
if this.props.firebase
is not equal to null
?
VerifyEmail = () => {
const { firebase } = this.props;
console.log(firebase);
if (firebase !== null) {
this.setState({ validCode: true, verifiedCode: true });
}
};
componentDidMount() {
const { firebase } = this.props;
if (firebase === null) {
this.intervalID = setInterval(() => this.VerifyEmail(), 1000);
} else if (firebase !== null) {
clearInterval(this.intervalID);
}
}
componentWillUnmount() {
clearInterval(this.intervalID);
}
Currently, this.VerifyEmail
is repeated and my attempt to clearInterval
if this.props.firebase
is not equal to null
does not run.
Also, if you have another method that will automatically action this.VerifyEmail()
on page render and when this.props.firebase
is not equal to null
. Please suggest.
Upvotes: 0
Views: 75
Reputation: 23705
componentDidMount
(or cDM
in short) runs just once when component is mounted. Later when you change props
provided it is not called. Upon props
is changed componentDidUpdate
is run. You may place your check there keeping in mind to check prevProps.firebase !== this.props.firebase
or you may stack in endless re-rendering. Just like that
componentDidUpdate(prevProps) {
const { firebase: prevFirebase } = this.prevProps;
const { firebase } = this.props;
if (!prevFirebase && firebase) { // null => not-null
this.intervalID = setInterval(() => this.VerifyEmail(), 1000);
}
if (prevFirebase && !firebase) { // not-null => null
clearInterval(this.intervalID);
}
}
Don't miss placing the same logic in componentDidMount
(for case when props.firebase
has been provided initially) and componentDidUpdate
(for case when props.firebase
is initially null
and later is assigned to props
).
But I believe there could be more DRY solution. Do you really need to render this component until data is retrieved? Do you render some placeholder until firebase
appears and data is loaded? If yes, then how about lift up data loading to parent component? Then your component would retrieve data through props
and it might have render as simple as (this.props.data && ...)
Upvotes: 1