Carlos Martinez
This spec is completed
Whenever the timer is started and the user reloads the timer page, there's a delay between the initial rendering and the update to the local state of the timer causing it to display 0 seconds
:
(I'm reloading the page)
Our goal is to display the correct current time of the timer as soon as the component is rendered and avoid the delay to show the state.
When the timerform
component gets mounted, it's state is being set to Date.now()
:
this.state = {
startTimeInMilliseconds: Date.now(),
timeElapsed: 0
};
This causes the initial render of the component to calculate the state based on the current time, and this is why it displays 0 seconds initially.
After the component gets mounted, the componentDidMount checks the localState to see if a timer was running last time the user was on the page:
componentDidMount() {
let timerState = localStorage.getItem('timerState');
if (timerState) {
// update state
}
}
The tick function (the one that is being executed with the inverval) updates the state each second calculating the time elapsed:
tick() {
// calculates time elapsed based on the current state
// updates the state
}
Our problem here, is that the tick function in the initial render uses uses the state set in the constructor, and because the interval runs each second, we have a 1 second delay between the initial rendering and the update of the values
To solve this I'm going to execute the tick
function with the state retrieved from the localState:
componentDidMount() {
let timerState = localStorage.getItem('timerState');
if (timerState) {
this.tick(timerState.startTimeMs);
}
}
And add the parameter to the tick function:
tick(startTime) {
// calculate time based on startTime if available
// update state
}
LGTM