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?
CodePudding user response:
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]);