Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React clock glithing after changing timezone

I’m trying to create a React app that will show time and weather based on user input.
To get weather data I send API request containing a name of the city to openweathermap and it returns json containing coordinates(lat, long) which I then use to make another request to ipgeolocation API to get the timezone of this coordinates.

Clock.jsx

const Clock = (props) => {

    const [clock, setClock] = useState()

    useEffect(() => {
        setInterval(() => {
            let time = new Date().toLocaleTimeString('en-US', { timeZone: props.timezone });
            setClock(time)
            console.log(time)
            console.log(clock)
        }, 1000);
    })

    return (
        <div className={props.className}>
            {clock}
        </div>
    )
}

After cahnging the timezone by making new API request time starts glitching. It frequently changes values between old and new time. What could be the problem?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

console.log(time)
console.log(time):

console.log(clock)
console.log(clock)

>Solution :

I can see a couple of issues:

First, you’re creating a new interval on every render of the component, because you’re not populating the right dependencies in useEffect. Since you’re depending on props.tinmezone to update the interval, it should be added to the dependency array. To fix this, you can add props.timezone to useEffect’s dependency array.

Second, you’re not clearing the interval in your cleanup part of the useEffect. To fix this, return clearInterval() in useEffect.

Here’s a working code snippet fixing both issues

  useEffect(() => {
    const interval = setInterval(() => {
      let time = new Date().toLocaleTimeString("en-US", {
        timeZone: props.timezone
      });
      setClock(time);
    }, 1000);

    return () => clearInterval(interval);
  }, [props.timezone]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading