Get only seconds from the current date in React.Js component - javascript

Hey i want to extract only the seconds from the current date and i am kind of blocked
This is my component and it only returns the whole date:
class Clock extends Component {
constructor(props) {
super(props);
this.state = {
time: new Date().toLocaleString()
};
}
componentDidMount() {
this.intervalID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.intervalID);
}
tick() {
this.setState({
time: new Date().toLocaleString()
});
}
render() {
return (
<div>{this.state.time}.</div>
);
}
}
export default Clock;

constructor(props) {
super(props);
this.state = {
time: new Date().getSeconds()
};
}
You can use the getSeconds(); method on the date object

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.

TypeError: this.state.toLocaleTimeString is not a function in React

This is code displaying what time is.
I set state to new Date() and give setState() new Date() as a parameter.
class Clock extends Component {
constructor(props) {
super(props)
this.state = new Date()
}
componentDidMount() {
this.timerID = setInterval(()=> this.tick(), 1000)
}
componentWillUnmount() {
clearInterval(this.timerID)
}
tick() {
this.setState(new Date())
}
render() {
return (
<div>
<h2>It is {this.state.toLocaleTimeString()}.</h2>
</div>
)
}
}
ReactDOM.render(<Clock />, document.getElementById('root'));
Running code, getting error like below
TypeError: this.state.toLocaleTimeString is not a function
Clock.render
29 | return (
30 | <div>
31 | <h1>Hello, world!</h1>
> 32 | <h2>It is {this.state.toLocaleTimeString()}.</h2>
| ^ 33 | </div>
34 | )
35 |
I can't understand what problem is.
How could I fix it?
You're not using any key to store/update the state, which is causing this error, since React doesn't find anything to update. I've used the key date to store and update the state on every second.
so, the state will be
this.state = {
date: new Date()
};
and the tick function update.
tick() {
this.setState({ date: new Date() });
}
and also the rendering part to use the state key.
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
Your updated code should be something like below.
import { render } from "react-dom";
import React from "react";
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {
date: new Date()
};
}
componentDidMount() {
this.timerID = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({ date: new Date() });
}
render() {
console.log(this.state);
return (
<div>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
const rootElement = document.getElementById("root");
render(<Clock />, rootElement);
React docs has some useful information regarding the state management and other related topics, which you should definitely take a look at, to understand how state works and re-renders UI accordingly.
Try using this.state = {date: new Date()}; in your state declarations instead.

Stop timer on button click in React

I'm working on an application and I have a timer with the current date, hour, minutes and seconds displayed. It is incremented every second. What I want to do is to stop the timer on a button click, but I'm not sure why the clearInterval() function doesn't work. My code is:
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = {
timer: "",
};
}
componentDidMount() {
//current time
setInterval(() => {
this.setState({
currentTime : new Date().toLocaleString()
})
}, 1000)
}
stopTimer = () => {
clearInterval(this.state.currentTime)
}
render() {
return (
<div>
<h4>Current time: {this.state.currentTime}</h4>
<Button onClick={this.stopTimer}>Stop timer</Button>
</div>
)
}
}
setInterval() result is the intervalID and you should use this for clearInterval().
this.state = {
...
intervalId: ""
};
...
const intervalId = setInterval(() => {
...
}, 1000);
this.setState({ intervalId });
...
clearInterval(this.state.intervalId);
You are using the clearInterval on wrong variable . You should do this.
I'm working on an application and I have a timer with the current date, hour, minutes and seconds displayed. It is incremented every second. What I want to do is to stop the timer on a button click, but I'm not sure why the clearInterval() function doesn't work. My code is:
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = {
timer: "",
intervalId: ""
};
}
componentDidMount() {
//current time
const intervalId = setInterval(() => {
this.setState({
currentTime : new Date().toLocaleString()
})
}, 1000);
this.setState({intervalId})
}
stopTimer = () => {
if (this.state.intervalId) {
clearInterval(this.state.intervelId)
}
}
render() {
return (
<div>
<h4>Current time: {this.state.currentTime}</h4>
<Button onClick={this.stopTimer}>Stop timer</Button>
</div>
)
}
}

Need to dynamically calculate refresh interval depending on time format passed in as prop

I have a react component that accepts an array of 2 moment.js time formats that will be used as props in the component to then render the time in a small clock widget in the format passed in. I need to dynamically calculate the refresh interval depending on time format passed in and being utilized. So if only needing seconds due to time format passed in being a second counter, interval refreshes every second, if only needing minutes, refresh rate will be around every minute. Couldn't find anything that has helped yet so asking for some advice. Thanks in advance. Here is my code, sorry it looks so rough right now.
import React, { Component } from 'react';
import moment from 'moment';
// Styles
import Style from 'Components/Header/Header.module.css';
class ClockWidget extends Component {
constructor() {
super()
this.state = {
time: moment().format('hh:mm a'),
toggle: true,
timerID: null
}
this.handleClick = this.handleClick.bind(this);
}
setTime() {
this.timerID = setInterval(() => {
if (this.state.toggle == true) {
this.setState({
time: moment().format(this.props.timeFormat[0])
})
} else if (this.state.toggle == false) {
this.setState({
time: moment().format(this.props.timeFormat[1])
})
}
console.log("State: ", this.state);
}, this.state.toggle ? 1000 : 60000);
}
componentDidMount() {
this.setTime();
}
handleClick() {
if (this.state.toggle) {
this.setState({ toggle: false })
} else {
this.setState({ toggle: true })
}
}
render() {
return (
<div onClick={this.handleClick}>
<p className={Style.action}> {this.state.time} </p>
</div>
)}
}
ClockWidget.defaultProps = {
timeFormat: ['hh:mm a', 'HH:mm']
}
export default ClockWidget;
do some changes...
in your state {
this.timerId = null
}
.
.
.
.
setTime(time = null, toggle = null) {
this.timerId = setInterval(() => {
if (this.state.toggle) {
this.setState({
time: moment().format(this.props.timeFormat[0]),
})
} else if (!this.state.toggle) {
this.setState({
time: moment().format(this.props.timeFormat[1]),
})
}
}, 1000)
}
componentDidMount() {
this.setTime();
}
componentWillUnmount() {
clearInterval(this.timerId)
}
and if you are gonna update then use update lifecycle methods togather with mount lifecycle methods

Warning react : setState(...): Can only update a mounted or mounting component

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op.
This is a react application, where a banner is fixed on the screen and passing random images. The way it was written is generating the warning in question.
import React from "react";
import Lightbox from "react-image-lightbox";
import logo from "./logo.png";
class Banner extends React.Component {
constructor(props) {
super(props);
this.state = {
images: [],
currentImage: logo,
isOpen: false,
sidebarOpen: true
};
}
async componentWillMount() {
await this.getBanners();
this.setState({ currentImage: this.state.images[0].url });
setInterval(async () => {
await this.getBanners();
}, 300000);
let i = 0;
setInterval(
() => {
this.setState({ currentImage: this.state.images[i].url });
if (i >= this.state.images.length - 1) {
i = 0;
} else {
i++;
}
},
10000,
i
);
}
async getBanners() {
const data = await (await fetch("/api/banners/active")).json();
if (data.true) {
this.setState({ images: data.true });
}
}
render() {
const { isOpen } = this.state;
return (
<div>
{isOpen && (
<Lightbox
mainSrc={this.state.currentImage}
onCloseRequest={() => this.setState({ isOpen: false })}
/>
)}
<footer>
<a>
<img
width={270}
height="200"
src={this.state.currentImage}
onClick={() => this.setState({ isOpen: true })}
alt="idk"
/>
</a>
</footer>
</div>
);
}
}
export default Banner;
Could anyone help improve this code?
You can put the numbers returned from setInterval on your instance and stop the intervals with clearInterval in componentWillUnmount so that they won't continue to run after the component has been unmounted.
class Banner extends React.Component {
constructor(props) {
super(props);
this.bannerInterval = null;
this.currentImageInterval = null;
this.state = {
images: [],
currentImage: logo,
isOpen: false,
sidebarOpen: true
};
}
async componentDidMount() {
await this.getBanners();
this.setState({ currentImage: this.state.images[0].url });
this.bannerInterval = setInterval(async () => {
await this.getBanners();
}, 300000);
let i = 0;
this.currentImageInterval = setInterval(
() => {
this.setState({ currentImage: this.state.images[i].url });
if (i >= this.state.images.length - 1) {
i = 0;
} else {
i++;
}
},
10000,
i
);
}
componentWillUnmount() {
clearInterval(this.bannerInterval);
clearInterval(this.currentImageInterval);
}
// ...
}
Use this template for any class-based component that has a state:
forgot about setState(), and use setComponentState declared down:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
// other fields...
isUnmounted: false,
};
}
componentWillUnmount() {
this.setState({ isUnmounted: true });
}
setComponentState = (values) => {
if (!this.state.isUnmounted) this.setState(values);
};
}

Categories

Resources