Handling methods in order in React - javascript

Hi im trying to code a Timer. My problem is that the countdown should start after clicking a button and when that status is changed from start to stop and vise versa. I cant figure out how to handle it and which level to put it.
ADDITIONAL INFO:
When clicking the button, it goes to the method handler. Changes the status with setstate() but it renders at the end. Which is to late for the countdown to start.
Here is the Game Component:
import React, { Component } from 'react';
import './Game.css';
import Timer from './Timer'
class Game extends Component {
constructor() {
super();
}
state = {
buttonStatus: {status:"Start" , classButton:"Button ButtonBackgroundColorGrey" },
dotclass : "",
timer: 60
}
componentDidMount() {
this.timersignal();
}
buttonclick = () =>{
(this.state.buttonStatus.status === "Start")
? this.setState({buttonStatus:{status:"Stop",classButton:"Button ButtonBackgroundColorRed"},dotclass:"Dot"})
: this.setState({buttonStatus:{status:"Start",classButton:"Button ButtonBackgroundColorGrey"},dotclass:""})
this.componentDidMount();
}
timersignal = () => {
if(this.state.buttonStatus.status === "Stop") {
this.Interval = setInterval(() =>{
this.setState(() => ({
timer : this.state.timer - 1
}))
},1000)
console.log("didMount start")
}
else(
console.log("didMount stop")
)
}
render() {
return (
<div>
<div className="Body-Container">
<h2 className="States"> Time </h2>
<Timer buttonstate= {this.state.timer}/>
<button className={this.state.buttonStatus.classButton} onClick={this.buttonclick}>{this.state.buttonStatus.status}</button>
</div>
</div>
);
}
}
export default Game;
Here is the Timer Component:
import React, { Component } from 'react';
import "./Timer.css";
class Timer extends Component {
render() {
return (
<h3 className="Timer">{this.props.buttonstate}</h3>
);
}
}
export default Timer ;

You just need one method and call it in componentDidMount and on click.
timerToggle = () =>{
if((this.state.buttonStatus.status === "Start") {
this.setState({buttonStatus:{status:"Stop",classButton:"Button ButtonBackgroundColorRed"},dotclass:"Dot"})
clearInterval(this.Interval);
}else{
this.setState({buttonStatus:{status:"Start",classButton:"Button ButtonBackgroundColorGrey"},dotclass:""}) ;
this.Interval = setInterval(() =>{
this.setState(() => ({
timer : this.state.timer - 1
}))
},1000)
}
}
componentDidMount() {
this.timerToggle();
}

The Final Answer:
timerToggle = () =>{
if(this.state.buttonStatus.status === "Start") {
this.setState({buttonStatus:{status:"Stop",classButton:"Button ButtonBackgroundColorRed"},dotclass:"Dot"})
this.Interval = setInterval(() =>{
this.setState(() => ({
timer : this.state.timer - 1
}))
},1000)
}
else{
this.setState({buttonStatus:{status:"Start",classButton:"Button ButtonBackgroundColorGrey"},dotclass:""}) ;
clearInterval(this.Interval);
}
}

Related

The counter in react executed twice in both given component

I am tring to make a simple counter and display it to the page.
But it renders unexpected o/p.
The counter counts a value twice in example 1 but works perfect as i want in example 2.
What is the reason for not working in ex.1.
What is the background process for this.
// Example: 1
import React, { Component } from 'react';
class Counter extends Component {
constructor() {
super()
this.state = {
count: 0,
isFirstTime: true
}
}
in() {
console.log('How many time function called?'); // consoled one time
if (this.state.isFirstTime) {
this.setState({
isFirstTime: false
})
setInterval(() => {
this.setState({
count: this.state.count + 1
})
}, 1000)
}
}
render() {
return (
<div>
{this.state.isFirstTime && this.in.apply(this)}
Counter: {this.state.count}
</div>
)
}
}
export default Counter;
// Example: 2
import React, { Component } from 'react';
let isFirstTime = true;
class Counter extends Component {
constructor() {
super()
this.state = {
count: 0
}
}
in() {
console.log('How many time function called?'); // consoled one time
if (isFirstTime) {
isFirstTime = false
setInterval(() => {
this.setState({
count: this.state.count + 1
})
}, 1000)
}
}
render() {
return (
<div>
{isFirstTime && this.in.apply(this)}
Counter: {this.state.count}
</div>
)
}
}
export default Counter;
I am running it on React.StrictMode.

why I am getting warning-Functions are not valid as a React child. .......?

I was learning about various lifecycle components, so I have a counter in my code, which can be increased or decreased using buttons and I have a seed generator which should be called on button click and it should change the value of the counter to seed, I have added function for the seed to be set to Number.parseInt(Math.random() * 100)
when I run the code, it gives warning in chrome,
also when I click on increment , the counter is set to () => this.setState({ seed: Number.parseInt(Math.random() * 100) })1 , and when I press decrement(click) the counter is set to NaN.
There was a similar question related to this warning but that code was not related to mine.
APP COMPONENT
import React from "react";
import Counter from "./Counter";
import "./App.css";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
mount: true,
ignoreProp: 0,
seed: 40
};
this.mountCounter = () => this.setState({ mount: true });
this.unmountCounter = () => this.setState({ mount: false });
this.ignoreProp = () => this.setState({ ignoreProp: Math.random() });
this.seedGenerator = () =>
this.setState({ seed: Number.parseInt(Math.random() * 100) });
}
render() {
let counter = null;
if (this.state.mount) {
counter = (
<Counter ignoreProp={this.state.ignoreProp} seed={this.seedGenerator} />
);
}
return (
<div className="App">
<button onClick={this.mountCounter} disabled={this.state.mount}>
Mount Counter
</button>
<button onClick={this.unmountCounter} disabled={!this.state.mount}>
Unmount Counter
</button>
<button onClick={this.ignoreProp}>Ignore Prop</button>
<button onClick={this.seedGenerator}>Generate seed</button>
{counter}
</div>
);
}
}
export default App;
COUNTER COMPONENT
import React from "react";
class Counter extends React.Component {
constructor(props) {
console.log("Constructor");
super(props);
this.state = {
counter: 0,
seed: 0
};
this.increment = () => this.setState({ counter: this.state.counter + 1 });
this.decrement = () => this.setState({ counter: this.state.counter - 1 });
}
static getDerivedStateFromProps(props, state) {
if (props.seed && state.seed !== props.seed) {
return {
seed: props.seed,
counter: props.seed
};
}
return null;
}
componentDidMount() {
console.log("Component Did Mount");
console.log("-------------------");
}
shouldComponentUpdate(nextProps, nextState) {
if (
nextProps.ignoreProp &&
this.props.ignoreProp !== nextProps.ignoreProp
) {
console.log("Should Component Update- DO NOT RENDER");
return false;
}
console.log("Should Component Update- RENDER");
return true;
}
render() {
console.log("Render");
return (
<div>
<button onClick={this.increment}>Increment</button>
<button onClick={this.decrement}>Decrement</button>
<div className="counter">Counter: {this.state.counter}</div>
</div>
);
}
componentDidUpdate(prevProps, prevState, snapshot) {
console.log("Component Did Update");
console.log("--------------------");
}
componentWillUnmount() {
console.log("Component Will Unmount");
console.log("----------------------");
}
}
export default Counter;
You pass seedGenerator, a function, as the seed prop down to Counter, and since you have
return {
seed: props.seed,
counter: props.seed
}
in getDerivedStateFromProps (likely a copy-paste typo?), the
Counter: {this.state.counter}
render fragment tries to render seedGenerator, a function.

React reusing a component with different state

I'm pretty new to React and trying to write my first app to get a better understanding.
What I'm trying to build is a simple time tracking tool where the user can start and stop a work timer.
Here you can see the design I came up with:
If the user clicks on the "start" button the working time Timer component should update every second. If the user clicks then on the "take a break" button the timer should stop and instead the break time Timer component should start ticking.
I would like to reuse the Timer component for both working and break timer and just set different states.
I already managed to do this but I don't know if this is a nice way or if this can be improved and make it more generic?
My Tracker component looks like this:
class Tracker extends Component {
constructor(props) {
super(props);
this.state = {
workTime: 0,
breakTime: 0,
isRunning: false,
timerType: 'workTimer'
}
}
startTimer(type) {
this.setState({
isRunning: true,
timerType: type
});
this.timerInterval = setInterval(() => {
this.updateTimer()
}, 1000);
}
stopTimer() {
this.setState({
isRunning: false
});
clearInterval(this.timerInterval);
}
toggleBreak(type) {
this.setState({
timerType: type
});
if (!this.state.isRunning && this.state.timerType === 'breakTimer') {
this.startTimer('breakTimer');
} else if (this.state.isRunning && this.state.timerType === 'breakTimer') {
this.stopTimer();
this.startTimer('workTimer');
} else {
this.stopTimer();
this.startTimer('breakTimer');
}
}
updateTimer() {
let state = null;
if (this.state.timerType === 'workTimer') {
state = {
workTime: this.state.workTime + 1000
};
} else {
state = {
breakTime: this.state.breakTime + 1000
};
}
this.setState(state);
}
render() {
return (
<div className="tracker">
<Timer time={ this.state.workTime }/>
<Timer time={ this.state.breakTime }/>
<TimerControls
isRunning={ this.state.isRunning }
start={ () => this.startTimer('workTimer') }
stop={ () => this.stopTimer() }
toggleBreak={ () => this.toggleBreak('breakTimer') }
/>
</div>
);
}
}
Controls component:
class TimerControls extends Component {
constructor(props) {
super(props);
}
render() {
const {isRunning, start, stop, toggleBreak} = this.props;
return (
<div className="tracker__control">
<button onClick={ start } disabled={ isRunning }>Start</button>
<button onClick={ toggleBreak }>Break</button>
<button onClick={ stop } disabled={ !isRunning }>Stop</button>
</div>
);
}
}
Timer component:
class Timer extends Component {
constructor(props) {
super(props);
}
render() {
const { time } = this.props;
return (
<div className="tracker__timer">{ timeFormat(time) }</div>
);
}
}
Is there a way to get rid of the timerType conditions?

Start the timer when button is clicked in React.Js

How do you make it so that whenever you click the start button, only then will the timer starts. Because right now, it starts at will.
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = { seconds: 0 };
}
tick() {
this.setState(prevState => ({
seconds: prevState.seconds + 1
}));
}
componentDidMount() {
this.interval = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return (
<div>
Seconds: {this.state.seconds}
<br />
<button onClick={this.tick}> Start </button>
</div>
);
}
}
ReactDOM.render(<Timer />, mountNode);
What should I put in the onClick attribute?
You will need to bind 'tick' to the component in the constructor and move the code for starting the timer from 'componentDidMount' to 'tick' like so:
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = { seconds: 0 };
this.tick = this.tick.bind(this); // bind to the component
}
tick() {
// start timer after button is clicked
this.interval = setInterval(() => {
this.setState(prevState => ({
seconds: prevState.seconds + 1
}));
}, 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return (
<div>
Seconds: {this.state.seconds}
<br />
<button onClick={this.tick}> Start </button>
</div>
);
}
}
ReactDOM.render(<Timer />, mountNode);
Hope that helps.
This is how we can achieve the same using React Hooks.
const Timer = () => {
const [isActive, setIsActive] = useState(false);
const [seconds, setSeconds] = useState(0);
useEffect(() => {
let timer = null;
if(isActive){
timer = setInterval(() => {
setSeconds((seconds) => seconds + 1);
}, 1000);
}
return () => {
clearInterval(timer);
};
});
return (
<div>
Seconds: {seconds}
<br />
<button onClick={()=>{
setIsActive(true);
}}> Start </button>
</div>
);
};

Why debounce doesnt invoke my function?

Im working on something with React and mobx.
I created an ImageCarousel Component where I show the image that was clicked.
I have a previous and a next buttons(which are themselves a Component), to move between images.
I tried to wrap those actions (prev and next) with lodash debounce,
but something fails on the way.
My current store has those actions:
prevCarousel
nextCarousel
debounceAction
debounceAction is just a Higher Order Function that get 2 parameters (fn, wait), and invoke lodash debounce with those parameters.
My CarouselButton component get through its props those actions I mantioned above. inside the Component I trigger with onClick event to invoke debounceAction(fn, wait) with the actual action (prev, or next).
Im not sure how to wrap my actions with debounce the right way.
I invoke debounceAction (the HOF that wraps the debounce) in the second code snippet (in CarouselButton Component).
do you see my mistake here?
galleryStore.jsx - current Store:
class GalleryStore {
// Observables
#observable images = [
// ....images
];
#observable carouselleButtons= {
next: "fa fa-chevron-right",
back: "fa fa-chevron-left"
}
#observable selectedImageIndex = null;
#observable hideCarousel = true;
#observable onTransition = false;
// Actions
selectImage = (index) =>{
this.selectedImageIndex = index;
}
toggleCarousel = () =>{
this.hideCarousel = !this.hideCarousel;
}
carouselNext = () => {
if(this.selectedImageIndex == this.images.length - 1) {
return;
}
this.onTransition = true;
setTimeout(() => {
this.selectedImageIndex = this.selectedImageIndex + 1;
this.onTransition = false;
},500)
}
carouselPrev = () => {
if(this.selectedImageIndex == 0) {
console.log('start of the collection');
return;
}
this.onTransition = true;
setTimeout(() => {
this.selectedImageIndex = this.selectedImageIndex - 1;
this.onTransition = false;
}, 500)
}
debounceAction = (fn, wait) => {
//lodash's debounce
return debounce(fn, wait);
}
carouselButton Component - here I Invoke the debounce:
// React's
import React from 'react';
// Styles
import CarouselButtonStyle from './carouselButtonStyle';
// CarouselButton Component
export default class CarouselButton extends React.Component {
debounce = (e) =>{
const { debounceAction } = this.props;
// -----> HERE I CALL DEBOUNCE ! <---------
e.stopPropagation();
debounceAction(this.buttonHandler, 400);
}
buttonHandler = (e) => {
const {limit, index, action, debounceAction} = this.props;
if(index == limit) return;
else action();
}
render(){
const {limit, index, icon, action, debounceAction} = this.props;
return(
<CarouselButtonStyle
onClick={(e) => {this.debounce(e)}}
className={ index == limit ? 'end-of-collection' : '' } >
<i className={icon} aria-hidden="true" />
</CarouselButtonStyle>
);
}
}
imageCarousel.jsx - carouselButton parent Component:
// React's
import React from 'react';
// Mobx-react's
import { observer, inject } from 'mobx-react';
// Styles
import ImageCarouselStyle from './imageCarouselStyle';
// Components
import ImgContainer from './imgContainer/imgContainer';
import CarouselButton from './carouselButton/carouselButton';
// ImageCarousel Component
#inject('galleryStore')
#observer
export default class ImageCarousel extends React.Component {
closeCarousel = () => {
this.props.galleryStore.toggleCarousel();
}
onKeyDown = (e) => {
const { keyCode } = e;
if(keyCode ===27) this.onEscHandler();
else if (keyCode == 37) this.onLeftArrow();
else if (keyCode == 39) this.onRightArrow();
else return;
}
onLeftArrow = () => { this.props.galleryStore.carouselPrev() }
onRightArrow = () => { this.props.galleryStore.carouselNext() }
onEscHandler = () => { this.closeCarousel() }
componentDidMount(){
document.addEventListener('keydown', this.onKeyDown, false);
}
render(){
return(
<ImageCarouselStyle
hidden={this.props.galleryStore.hideCarousel}
onClick={this.closeCarousel} >
<CarouselButton action={'prev'}
icon={this.props.galleryStore.carouselleButtons.back}
action={this.props.galleryStore.carouselPrev}
limit={0}
index={this.props.galleryStore.selectedImageIndex}
debounceAction={this.props.galleryStore.debounceAction} />
<ImgContainer
images={this.props.galleryStore.images}
imgIndex={this.props.galleryStore.selectedImageIndex}
onTransition={this.props.galleryStore.onTransition}/>
<CarouselButton action={'next'}
icon={this.props.galleryStore.carouselleButtons.next}
action={this.props.galleryStore.carouselNext}
limit={this.props.galleryStore.amountOfImages}
index={this.props.galleryStore.selectedImageIndex}
debounceAction={this.props.galleryStore.debounceAction} />
</ImageCarouselStyle>
);
}
}
The issue is that you have to return debounceAction from CarouselButton's debounce method.
debounce = (e) =>{
const { debounceAction } = this.props;
// -----> HERE I CALL DEBOUNCE ! <---------
e.stopPropagation();
debounceAction(this.buttonHandler, 400);
// -^^^ must return here
}
However, I would suggest going a step further to avoid future confusion. Simply invoke lodash's debounce when you need it, rather than rewriting it multiple times in your code and leading to questionable method names.
Here is the most basic example of how you can wrap a click handler:
class Button extends React.Component {
handleClick = _.debounce((e) => {
alert('debounced click reaction')
}, 1000)
render() {
return <button onClick={this.handleClick}>CLICK ME</button>
}
}
ReactDOM.render(
<Button />,
document.getElementById('app')
);
<div id="app"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Categories

Resources