ReactJS Stopwatch, how to handle localstorage data - javascript

i have component where i count time (Stopwatch). everything is working fine. Start, stop of the clock reset. I wanted to add functionality that when i stop clock (handleTimerStop) set current state to localstorage in case if i close browser and want to return and want to start where i left clock paused. So when i stop clock items are setup to localstorage but when i want to restart clock it doesn't take data from local storage but start from scratch. Could you please help? also it will be great if someone can optimsie my code becasue i feel it can be done better.
thanks
import React, { Component } from "react";
export default class Timer extends Component {
constructor(props) {
super(props);
this.state = {
timerStarted: false,
timerStopped: true,
hours: 0,
minutes: 0,
seconds: 0
};
}
componentDidMount() {
if (!localStorage.getItem("sec") === null) {
this.setState({
seconds: localStorage.getItem("sec")
});
}
if (!localStorage.getItem("min") === null) {
this.setState({
seconds: localStorage.getItem("min")
});
}
if (!localStorage.getItem("hour") === null) {
this.setState({
seconds: localStorage.getItem("hours")
});
}
}
handleTimerStart = e => {
e.preventDefault();
if (localStorage.getItem("sec") === null) {
this.setState({
seconds: 0
});
} else {
this.setState({
seconds: localStorage.getItem("sec")
});
}
if (localStorage.getItem("min") === null) {
this.setState({
minutes: 0
});
} else {
this.setState({
minutes: localStorage.getItem("min")
});
}
if (localStorage.getItem("hour") === null) {
this.setState({
hours: 0
});
} else {
this.setState({
hours: localStorage.getItem("hour")
});
}
if (this.state.timerStopped) {
this.timer = setInterval(() => {
this.setState({ timerStarted: true, timerStopped: false });
if (this.state.timerStarted) {
if (this.state.seconds >= 60) {
this.setState(prevState => ({
minutes: prevState.minutes + 1,
seconds: localStorage.getItem("sec")
}));
}
if (this.state.minutes >= 60) {
this.setState(prevState => ({
hours: prevState.hours + 1,
minutes: localStorage.getItem("min"),
seconds: localStorage.getItem("sec")
}));
}
this.setState(prevState => ({ seconds: prevState.seconds + 1 }));
}
}, 1000);
}
};
handleTimerStop = () => {
this.setState({ timerStarted: false, timerStopped: true });
clearInterval(this.timer);
localStorage.setItem("sec", this.state.seconds);
localStorage.setItem("min", this.state.minutes);
localStorage.setItem("hour", this.state.hours);
};
handelResetTimer = () => {
this.setState({
timerStarted: false,
timerStopped: true,
hours: 0,
minutes: 0,
seconds: 0
});
};
render() {
return (
<div className="container">
<h2 className="text-center"> React Based Timer </h2>
<div className="timer-container">
<div className="current-timer">
{this.state.hours +
":" +
this.state.minutes +
":" +
this.state.seconds}
</div>
<div className="timer-controls">
<button className="btn btn-success" onClick={this.handleTimerStart}>
Start Timer
</button>
<button className="btn btn-alert" onClick={this.handleTimerStop}>
Stop Timer
</button>
<button className="btn btn-info"> Capture Time </button>
<button className="btn btn-danger" onClick={this.handelResetTimer}>
{" "}
Reset!{" "}
</button>
</div>
</div>
</div>
);
}
}

These comparations are your problem.
!null === null or !'23' === null ... false always.
if (!localStorage.getItem("sec") === null) {
this.setState({
seconds: localStorage.getItem("sec")
});
}
if (!localStorage.getItem("min") === null) {
this.setState({
seconds: localStorage.getItem("min")
});
}
if (!localStorage.getItem("hour") === null) {
this.setState({
seconds: localStorage.getItem("hours")
});
}

This ain't an answer to your concrete question, but imo. a better approach at your code
This implementation is
independant of the render interval,
only writes to localStorage when you start/stop/reset it
and is not getting out of sync (even if it does not get rendered at all)
.
import React, { Component } from "react";
export default class Timer extends Component {
constructor(props) {
super(props);
try {
this.state = JSON.parse(localStorage.getItem(this.props.localStorage));
} catch (error) {}
if (!this.state) {
this.state = this.saveChanges({
running: false,
value: 0
});
}
}
componentWillMount() {
if (this.state.running) {
this.timer = setInterval(
() => this.forceUpdate(),
this.props.interval | 0
);
}
}
componentWillUnmount() {
if (this.state.running) {
clearInterval(this.timer);
}
}
saveChanges(state) {
console.log("saveChanges", this.props.localStorage, state);
if (this.props.localStorage) {
localStorage.setItem(this.props.localStorage, JSON.stringify(state));
}
return state;
}
start = () => {
const now = Date.now();
this.setState(({ running, value }) => {
if (running) return null;
this.timer = setInterval(
() => this.forceUpdate(),
this.props.interval | 0
);
return this.saveChanges({
running: true,
value: value - now
});
});
};
stop = () => {
const now = Date.now();
this.setState(({ running, value }) => {
if (!running) return null;
clearInterval(this.timer);
return this.saveChanges({
running: false,
value: value + now
});
});
};
reset = () => {
const now = Date.now();
this.setState(({ running, value }) => {
return this.saveChanges({
running: false,
value: 0
});
//just reset the timer to 0, don' stop it
//return this.saveChanges({
// running,
// value: running? -now: 0
//});
});
};
render() {
const {
start, stop, reset,
state: { running, value }
} = this;
const timestamp = running ? Date.now() + value : value;
const h = Math.floor(timestamp / 3600000);
const m = Math.floor(timestamp / 60000) % 60;
const s = Math.floor(timestamp / 1000) % 60;
const ms = timestamp % 1000;
const _ = (nr, length = 2, padding = 0) =>
String(nr).padStart(length, padding);
return (
<div className="container">
<h2 className="text-center"> React Based Timer </h2>
<div className="timer-container">
<div className="current-timer">
{_(h) + ":" + _(m) + ":" + _(s) + "." + _(ms, 3)}
</div>
<div className="timer-controls">
<button className="btn btn-success" onClick={start}>
Start Timer
</button>
<button className="btn btn-alert" onClick={stop}>
Stop Timer
</button>
<button className="btn btn-danger" onClick={reset}>
Reset!
</button>
</div>
</div>
</div>
);
}
}
check this Sandbox out

Related

How to get Pomodoro Clock to work on CodePen?

The following code for a React Pomodoro Clock has been input into CodePen exactly into the CodePen JS editor and HTML editor, and then save clicked. However, CodePen does not display the Pomodoro Clock, and where the clock should appear there is only a blank orange page. There is no indication why on CodePen. Actual link: https://codepen.io/controlunit/pen/dyMrMxy Any help would be greatly appreciated.
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './style.css';
/*
* A simple React component
*/
const initState = {
breakLength: 5,
sessionLength: 25,
init: 'session',
stateIndex: 0,
timeLeft: undefined,
timeLeftSeconds: undefined,
started: false,
intervalFunc: undefined
}
const states = [ { name: 'session', duration: 1500 }, { name: 'break', duration: 300 } ]
const secondsToMins = (time) => {
let converted = ('0' + Math.floor(time / 60)).slice(-2) + ':' + ('0' + Math.floor(time % 60)).slice(-2);
return converted;
}
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = initState;
this.breakDecrement = this.breakDecrement.bind(this);
this.breakIncrement = this.breakIncrement.bind(this);
this.sessionDecrement = this.sessionDecrement.bind(this);
this.sessionIncrement = this.sessionIncrement.bind(this);
this.startStop = this.startStop.bind(this);
this.reset = this.reset.bind(this);
}
componentDidMount() {
let sessionSeconds = this.state.sessionLength * 60;
this.setState({ timeLeftSeconds: sessionSeconds });
this.setState({ timeLeft: secondsToMins(sessionSeconds) });
}
breakDecrement() {
// decrements the breakLength and the breakSeconds
// breakLength is only a number ie. 5 (does not show seconds)
// breakSeconds is that nunber converted into seconds
let breakLength = this.state.breakLength - 1;
if (breakLength > 0 && breakLength < 61){
this.setState({ breakLength: breakLength });
let breakSeconds = breakLength * 60;
states[1]['duration'] = breakSeconds;
}
}
breakIncrement() {
// same as decrement except does increment
let breakLength = this.state.breakLength + 1;
if (breakLength > 0 && breakLength < 61){
this.setState({ breakLength: breakLength });
let breakSeconds = breakLength * 60;
states[1]['duration'] = breakSeconds;
}
}
sessionDecrement() {
// decrements the sessionLength and the sessionSeconds
// sessionLength is only a number ie. 25 (does not show seconds)
// sessionSeconds is that nunber converted into seconds
let sessionLength = this.state.sessionLength - 1;
if (sessionLength > 0 && sessionLength < 61){
states[0]['duration'] = sessionLength*60;
this.setState(prevState => ({
sessionLength: prevState.sessionLength-1,
timeLeftSeconds: (prevState.sessionLength-1)*60,
timeLeft: secondsToMins((prevState.sessionLength-1)*60)})
);
}
}
sessionIncrement() {
// same as decrement except does increment
let sessionLength = this.state.sessionLength + 1;
if (sessionLength > 0 && sessionLength < 61){
states[0]['duration'] = sessionLength*60;
this.setState(prevState => ({
sessionLength: prevState.sessionLength+1,
timeLeftSeconds: (prevState.sessionLength+1)*60,
timeLeft: secondsToMins((prevState.sessionLength+1)*60)})
);
}
}
startStop(id) {
// starts the countDown, which runs continuously until the start/stop button
// is pressed again, which pauses the countdown.
// the id parameter is used by countDown to play the audio beep
if(!this.state.started){
this.countDown(id);
this.setState({ started: true});
}
// pauses the countDown
if(this.state.started){
let intervalFunc = this.state.intervalFunc;
clearInterval(intervalFunc);
this.setState({ started: false});
}
}
reset() {
let intervalFunc = this.state.intervalFunc;
clearInterval(intervalFunc);
// reset state to default values
this.setState({ breakLength: 5 });
this.setState({ sessionLength: 25 });
this.setState({ init: 'session' });
this.setState({ timeLeftSeconds: 1500})
this.setState({ timeLeft: '25:00' });
this.setState({ stateIndex: 0 });
this.setState({ started: false });
this.setState({ intervalFunc: undefined });
}
countDown(id){
// set the function to a variable and set state to it, so the function
// can be paused with clearInterval()
var intervalFunc = setInterval(() => down(this.state.timeLeftSeconds--), 1000);
this.setState({intervalFunc: intervalFunc});
const down = (time) =>
{
if(time > 0){
// converts seconds to MM:SS at every t-minus
this.setState({ timeLeft: secondsToMins(time)});
console.log(time);
console.log(this.state.timeLeft);
}
if (time <= 0) {
let sound = document.getElementById(id).childNodes[0];
sound.play();
let stateIndex = (this.state.stateIndex + 1) % states.length;
this.setState({ stateIndex: stateIndex});
this.setState({ timeLeftSeconds: states[stateIndex].duration});
this.setState({ init: states[stateIndex].name});
this.setState({ timeLeft: secondsToMins(time)});
console.log(time);
console.log(this.state.timeLeft);
console.log(this.state.init);
}
}
}
render() {
return (
<div id="clock">
<h1 id="title">25-5 Clock</h1>
<div>
<p id="break-label">Break Length</p>
<p id="break-length">{this.state.breakLength}</p>
<button id="break-decrement" onClick={e => this.breakDecrement()}> Decrease </button>
<button id="break-increment" onClick={e => this.breakIncrement()}> Increase </button>
</div>
<div>
<p id="session-label">Session Length</p>
<p id="session-length">{this.state.sessionLength}</p>
<button id="session-decrement" onClick={e => this.sessionDecrement()}> Decrease </button>
<button id="session-increment" onClick={e => this.sessionIncrement()}> Increase </button>
</div>
<hr/>
<div>
<p id="timer-label">{this.state.init}</p>
<p id="time-left">{this.state.timeLeft}</p>
<button id="start_stop" onClick={e => this.startStop(e.target.id)}><audio id="beep" src='./beep.mp3'></audio> start/stop </button>
<button id="reset" onClick={e => this.reset()}> reset </button>
</div>
</div>
);
}
};
/*
* Render the above component into the div#app
*/
ReactDOM.render(<Clock />, document.getElementById("app"));
index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>25-5 Clock</title>
<style>
</style>
</head>
<body>
<main>
<div id="app"></app>
</main>
</body>
</html>
It's because you're using JSX in your javascript without transpiling it. Go into codepen's settings and under the javascript tab select 'babel' as the javascript preprocessor.

Bug in my react Stopwatch code. Issue with clearInterval()?

I've been trying to build a simple stopwatch application in React. The app is rendering okay but the stop and clear buttons are not working. Once started the timer will just keep on running.
Been banging my head on the keyboard for awhile now with this. Any help appreciated.
Thanks.
class Stopwatch extends Component {
state = {
status: false,
runningTime: 0
};
handleClick = () => {
this.setState(state => {
if (state.status) {
clearInterval(this.timer);
} else {
const startTime = Date.now() - this.state.runningTime;
this.timer = setInterval(() => {
this.setState({ runningTime: Date.now() - startTime });
});
}
return { status: !state.status };
});
};
handleReset = () => {
clearInterval(this.timer);
this.setState({ runningTime: 0, status: false });
};
componentWillUnmount() {
clearInterval(this.timer);
}
render() {
const { status, runningTime } = this.state;
return (
<div>
<p>{runningTime}ms</p>
<button onClick={this.handleClick}>{status ? 'Stop' : 'Start'}</button>
<button onClick={this.handleReset}>Reset</button>
</div>
);
}
}

How to reset interval and call api with interval in a function in react js

Hello I wanted to reset my set interval whenever my function is been called iam calling my interval in componentDidmount in react js and I want it to reset previous interval whenever that function is called iam also changing the value of api in that same function and now i want it to behave with the changes. The function is all three of the keyPressed Below is my code.
import React, { Component } from "react";
import { HotKeys } from "react-hotkeys";
import Axios from "axios";
class Test extends Component {
constructor(props) {
super(props);
this.state = {
seconds: 3,
color: null,
items: [],
currentItem: [],
index: 0
};
this.handleChange = this.handleChange.bind(this);
this.keyMap = {
DONT_APPLIES: ["a", "A"],
APPLIES: ["s", "S"],
STRONGLY_APPLIES: ["d", "D"]
};
this.handlers = {
DONT_APPLIES: e => {
this.keyPressed();
},
APPLIES: e => {
this.keyPressed1();
},
STRONGLY_APPLIES: e => {
this.keyPressed2();
}
};
}
keyPressed(e) {
const { index, items } = this.state;
const nextQuestion = index + 1;
this.setState({ currentItem: items[nextQuestion], index: nextQuestion });
console.log(this.state);
}
keyPressed1(e) {
const { index, items } = this.state;
const nextQuestion = index + 1;
this.setState({ currentItem: items[nextQuestion], index: nextQuestion });
console.log(this.state);
}
keyPressed2(e) {
const { index, items } = this.state;
const nextQuestion = index + 1;
this.setState({ currentItem: items[nextQuestion], index: nextQuestion });
console.log(this.state);
}
handleChangeColor = newColor => {
this.setState({
color: newColor
});
};
componentDidMount() {
this.myInterval = setInterval(() => {
const { seconds } = this.state;
if (seconds > 0) {
this.setState(({ seconds }) => ({
seconds: seconds - 1
}));
} else if (seconds == 0) {
return this.handleChangeColor("#840000");
}
}, 1000);
Axios.get("https://jsonplaceholder.typicode.com/users")
.then(response => {
console.log(response);
this.setState({
items: response.data.result.items,
currentItem: response.data.result.items[0],
index: 0
});
})
.catch(error => {
console.log(error);
});
}
componentWillUnmount() {
clearInterval(this.myInterval);
}
render() {
const { seconds } = this.state;
const timebox = {
width: "50px",
height: "20px"
};
const { currentItem } = this.state;
return (
<HotKeys keyMap={this.keyMap} handlers={this.handlers}>
<div id="wrapper" class="myleaty">
<div class="myleaty-holder">
<div class="container">
<div style={{ background: this.state.color }} class="myleaty-box">
<div style={timebox}>
<h2>{seconds}</h2>
</div>
<div class="logo">
<a href="#">
<img src="images/logo.png" alt="leaty" />
</a>
</div>
<p key={currentItem.id}>{currentItem.pqDetail}</p>
<div class="btn-row">
<button className="btn btn1">Does not Applies</button>
<button className="btn">Applies</button>
<button className="btn btn1">Strongly Applies</button>
</div>
</div>
</div>
</div>
</div>
</HotKeys>
);
}
}
export default Test;

A click to start the countdown timer and a second one to Pause the timer in the same button

I want to click on (Start/Pause) Button in order start the coundown in the first click and the second click to pause it.It should be two options in the same button to start and pause the timer.
Here a descriptive image :
A created a separated button for start and pause the countdown but i want to make them in the same button.
Here my React Js code:
import React from "react";
export default class Timer extends React.Component {
constructor(props) {
super(props);
this.state = {
secondsElapsed: 1800000 / 1000 //time in seconds
};
}
getHours() {
return ("0" + Math.floor(this.state.secondsElapsed / 3600)).slice(-2);
}
getMinutes() {
return ("0" + Math.floor((this.state.secondsElapsed % 3600) / 60)).slice(
-2
);
}
getSeconds() {
return ("0" + (this.state.secondsElapsed % 60)).slice(-2);
}
startTime() {
var _this = this;
this.countdown = setInterval(function() {
_this.setState({ secondsElapsed: _this.state.secondsElapsed - 1 });
}, 1000);
}
resetTime() {
this.reset = this.setState({
secondsElapsed: (this.state.secondsElapsed = 0)
});
}
pauseTime() {
clearInterval(this.countdown);
}
render() {
return (
<div className="App">
<div className="timer-container">
<div className="bloc-timer"> {this.getHours()}</div>
<div className="bloc-timer"> :{this.getMinutes()}</div>
<div className="bloc-timer"> :{this.getSeconds()}</div>
</div>
<div>
<button onClick={() => this.startTime()}>Start</button>
<button onClick={() => this.pauseTime()}>Pause</button>
<button onClick={() => this.resetTime()}>Reset</button>
</div>
</div>
);
}
}
You can add an additional state variable isActive that keeps track of if your timer is active or not and choose what function to call when clicking the button based on that.
Example
class Timer extends React.Component {
state = {
isActive: false,
secondsElapsed: 1800000 / 1000 //time in seconds
};
getHours() {
return ("0" + Math.floor(this.state.secondsElapsed / 3600)).slice(-2);
}
getMinutes() {
return ("0" + Math.floor((this.state.secondsElapsed % 3600) / 60)).slice(
-2
);
}
getSeconds() {
return ("0" + (this.state.secondsElapsed % 60)).slice(-2);
}
startTime = () => {
this.setState({ isActive: true });
this.countdown = setInterval(() => {
this.setState(({ secondsElapsed }) => ({
secondsElapsed: secondsElapsed - 1
}));
}, 1000);
};
resetTime = () => {
clearInterval(this.countdown);
this.setState({
secondsElapsed: 1800000 / 1000,
isActive: false
});
};
pauseTime = () => {
clearInterval(this.countdown);
this.setState({ isActive: false });
};
render() {
return (
<div className="App">
<div className="timer-container">
<span className="bloc-timer"> {this.getHours()}</span>
<span className="bloc-timer"> :{this.getMinutes()}</span>
<span className="bloc-timer"> :{this.getSeconds()}</span>
</div>
<div>
<button
onClick={this.state.isActive ? this.pauseTime : this.startTime}
>
Start/Pause
</button>
<button onClick={this.resetTime}>Reset</button>
</div>
</div>
);
}
}
ReactDOM.render(<Timer />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
You can add a Boolean to check the state of your timer. And trigger timer start or stop depending on its value. Basically add another function to change the state, and call startTime if it hasn't been started, and pauseTime it if has been started.

In React, how should I pass a starting elapsed time to a stopwatch component and start a running incrementer from that elapsed time?

I can get a static elapsed seconds to display based on the pulled start time but I can't get the elapsed seconds to then continue counting. I know I probably shouldn't be using the props to update a state in the child but even without that I couldn't get it to work and tried that as a workaround. Any help is appreciated.
Parent looks like this:
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
elapsedSeconds: -1
};
this.changeElapsedSecondsParent = this.changeElapsedSecondsParent.bind(this);
}
changeElapsedSecondsParent(newElapsed) {
this.setState({
elapsedSeconds: newElapsed
});
}
render() {
const { elapsedSeconds } = this.state;
return (
<div>
<Stopwatch
elapsedSeconds={elapsedSeconds}
changeElapsed={this.changeElapsedSecondsParent}
/>
</div>
);
}
}
Child stopwatch looks like this:
const formattedSeconds = (sec) =>
~~(sec / 60) +
':' +
('0' + sec % 60).slice(-2)
export class Stopwatch extends React.Component {
constructor(props) {
super(props);
this.state = {
secondsElapsed: -1,
laps: [],
lastClearedIncrementer: null
};
this.incrementer = null;
this.handleStartClick = this.handleStartClick.bind(this);
this.handleStopClick = this.handleStopClick.bind(this);
this.handleResetClick = this.handleResetClick.bind(this);
this.handleLapClick = this.handleLapClick.bind(this);
}
componentDidMount() {
if(this.state.secondsElapsed < 0) {
const getElapsedTime = async () => {
try{
const response = await fetch(`api url`);
if(response.ok){
let jsonResponse = await response.json();
/* start getting seconds elapsed since start */
let currentServerTime = new Date(jsonResponse[0].currentTimeStamp).getTime() /1000;
let currentD = Math.floor(new Date().getTime()/1000);
let deltaDate = (currentServerTime-currentD);
let raceStartTime = new Date(jsonResponse[0].startTime).getTime()/1000 - deltaDate;
let secondsElapsedSinceStart = currentD - raceStartTime;
/* end getting seconds elapsed since start */
this.props.changeElapsed(secondsElapsedSinceStart);
}
}
catch(error){
console.log(error);
}
}
getElapsedTime();
let newElapsed = this.props.elapsedSeconds;
this.incrementer = setInterval( () =>
this.setState({
secondsElapsed: newElapsed + 1
})
, 1000);
} else {
this.incrementer = setInterval( () =>
this.setState({
secondsElapsed: this.state.secondsElapsed + 1
})
, 1000);
}
}
handleStartClick() {
/* start post request */
const pushTime = async () => {
try {
const response = await fetch('apiurl', {
method: 'POST',
body: JSON.stringify({"startTime": "'2018-08-26 16:57:09'"})
})
if(response.ok){
const jsonResponse = await response.json();
return jsonResponse;
}
throw new Error('Request failed!');
} catch(error) {
console.log(error);
}
}
pushTime();
}
handleStopClick() {
clearInterval(this.incrementer);
this.setState({
lastClearedIncrementer: this.incrementer
});
}
handleResetClick() {
clearInterval(this.incrementer);
this.setState({
secondsElapsed: 0,
laps: []
});
}
handleLapClick() {
this.setState({
laps: this.state.laps.concat([this.props.elapsedSeconds])
})
}
render() {
return (
<div className="stopwatch">
<h1 className="stopwatch-timer">{formattedSeconds(this.state.secondsElapsed)}</h1>
{(this.props.elapsedSeconds === 0 ||
this.incrementer === this.state.lastClearedIncrementer
? <Button className="start-btn" onClick={this.handleStartClick.bind(this)}>start</Button>
: <Button className="stop-btn" onClick={this.handleStopClick.bind(this)}>stop</Button>
)}
{(this.props.elapsedSeconds !== 0 &&
this.incrementer !== this.state.lastClearedIncrementer
? <Button onClick={this.handleLapClick.bind(this)}>lap</Button>
: null
)}
{(this.props.elapsedSeconds !== 0 &&
this.incrementer === this.state.lastClearedIncrementer
? <Button onClick={this.handleResetClick.bind(this)}>reset</Button>
: null
)}
<ul className="stopwatch-laps">
{ this.state.laps.map((lap, i) =>
<li className="stopwatch-lap"><strong>{i + 1}</strong>/ {formattedSeconds(lap)}</li>)
}
</ul>
</div>
);
}
}
const Button = (props) =>
<button type="button" {...props} className={"btn " + props.className } />;
I found it easier to define a constant in the constructor like:
this.deltaTime = null;
Then I created a changeDeltaTime function:
changeDeltaTime(newTime) {
this.deltaTime = newTime
}
lastly, I updated that deltaTime inside the promiseand after the response within the componentDidUpdate() lifecycle method.
await this.changeDeltaTime(deltaDate);
In render, I waited the promise to be resolved through a prop passed by parent
return !this.props.finishedGet ? <span>Waiting on fetch...</span> : (this.renderStopwatch(this.state.time))
This also involves the renderStopwatch function to be created but it basically just houses what should be created once the promise resolves.

Categories

Resources