Hello,
I’m still kind of new to React Redux so, as an excercise, I’m refactoring React projects.
I found this tutorial of a React Stopwatch…
…but I haven’t figure it out how to fix it.
I know there’s something wrong with the set Interval but I don’t know how to fix it.
Here’s my code
const START_TIMER = 'START_TIMER'
const STOP_IT = 'STOP_IT'
const RESUME_IT = 'RESUME_IT'
const startT = () => {
return {
type: START_TIMER
}
}
const stopT = () => {
return {
type: STOP_IT
}
clearInterval(this.timer)
}
const resumeT = () => {
return {
type: RESUME_IT
}
}
const initialState = {
timerOn: false,
timerStart: 0,
timerTime: 0,
timer: ''
}
const reducer = (state = initialState, action) => {
switch (action.type) {
case START_TIMER:
return {
timerOn: true,
timerTime: state.timerTime,
timerStart: Date.now() - state.timerTime,
timer: setInterval(() => {
timerTime: Date.now() - state.timerStart
}, 10)
}
case STOP_IT:
return {
timerOn: false
}
case STOP_IT:
return {
timerStart: 0,
timerTime: 0
}
default: return state;
}
}
const store = Redux.createStore(reducer);
// React:
const Provider = ReactRedux.Provider;
const connect = ReactRedux.connect;
class Presentational extends React.Component {
constructor(props){
super(props);
}
render(){
const { timerTime } = this.props;
let centiseconds = ("0" + (Math.floor(timerTime / 10) % 100)).slice(-2)
let seconds = ("0" + (Math.floor(timerTime / 1000) % 60)).slice(-2)
let minutes = ("0" + (Math.floor(timerTime / 60000) % 60)).slice(-2)
let hours = ("0" + Math.floor(timerTime / 3600000)).slice(-2)
return(
<div>
{hours} : {minutes} : {seconds} : {centiseconds}<br/>
{this.props.timerOn === false && this.props.timerTime === 0 && (
<button onClick={this.props.startTimer}>Start</button>
)}
{this.props.timerOn === true && (
<button onClick={this.props.stopTimer}>Stop</button>
)}
{this.props.timerOn === false && this.props.timerTime > 0 && (
<button onClick={this.props.startTimer}>Resume</button>
)}
{this.props.timerOn === false && this.props.timerTime > 0 && (
<button onClick={this.props.resetTimer}>Reset</button>
)}
</div>
)
}
}
const mapStateToProps = (state) => {
return {
timerOn: state.timerOn,
timerStart: state.timerStart,
timerTime: state.timerTime,
timer: state.timer
}
}
const mapDispatchToProps = (dispatch) => {
return {
startTimer: () => dispatch({type: START_TIMER }),
stopTimer: () => dispatch({type: STOP_IT }),
resetTimer: () => dispatch({type: RESUME_IT })
};
}
const Container = connect(mapStateToProps, mapDispatchToProps)(Presentational);
class AppWrapper extends React.Component {
render() {
return (
<Provider store={store}>
<Container/>
</Provider>
);
}
};
ReactDOM.render(<AppWrapper />, document.getElementById('app'));
Can somebody help?
Thanks a lot!