How to do countdown with API
Following with the previous blog post on how to get the time, convert it to AEST time and using the diff
to identify how many minutes left till the train comes, we want to have a count down according to the local time change so that we know when the train is coming.
I didn’t want to constantly keep calling the API since I have a limit of 60,000 hits. So we’re going to use if
statement, set a constant -1
for the countdown and re-set the state every time for new countdown.
We had the countdown state that we stored in const { countdown } = this.state;
which is essentially the same as const countdown = this.state.countdown;
Then we’re going to set the minus one so the number decreases let newCountdown = countdown -1;
So when the state gets updated, we have the new countdown
this.setState({ countdown: newCountdown });
The if
statement shows that if the countdown reaches 0, you want to clear the interval and have the text written “arrived!”
What if I press the button again?
IF you press the button again to call another API, the timer will not clear the current data and and the original will keep counting down as well as the new API call countdown will also be counting down. We needed something to clear the data
Use React Life cycle method
ComponentWillUnmount( ) will unmount the old data and update the API call so that the countdown will not override the old data.
componentWillUnmount(){ clearInterval(this.state.countdown) }