I'm creating an event countdown on one of my pages. It works well, but there is a warning:
```
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
```
Here is my entire code:
import React, {useState, useRef, useEffect} from 'react'
import Layout from '../components/layout'
import MainEvent from '../components/events/MainEvent'
import MarginalEvent from '../components/events/MarginalEvent'
import SEO from '../components/SEO'
import { graphql } from 'gatsby'
import {navigate} from 'gatsby-link'
import { format } from 'date-fns'
const Events = ({data}) => {
const {allStrapiEvents:{nodes:events}} = data
const found = events.find((event)=> {
const today = new Date()
const myday = new Date(event.date)
if(myday > today) {
return event
} else {
return null
}
})
const [timerDays, setTimerDays] = useState('00');
const [timerHours, setTimerHours] = useState('00');
const [timerMinutes, setTimerMinutes] = useState('00');
const [timerSeconds, setTimerSeconds] = useState('00');
let interval = useRef();
const startTimer = () => {
const countdownDate = new Date(found.date).getTime();
interval = setInterval(()=> {
const now = new Date().getTime();
const distance = countdownDate - now;
let days = Math.floor(distance / (1000 * 60 * 60 * 24));
let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((distance % (1000 * 60)) / 1000);
if(distance < 0) {
clearInterval(interval.current)
} else {
setTimerDays(days)
setTimerHours(hours)
setTimerMinutes(minutes)
setTimerSeconds(seconds)
}
}, 1000)
}
useEffect(()=> {
const someref = interval.current
startTimer()
return ()=> {
clearInterval(someref)
}
})
return (
<Layout>
<SEO title="Events" />
<div className="py-5">
<MainEvent title={found.title}
image={found.photo.childImageSharp.fluid.src}
slug={found.slug}
setDays={timerDays}
setHours={timerHours}
setMinutes={timerMinutes}
setSeconds={timerSeconds}
/>
<div className="flex flex-wrap justify-center">
{events.map((event)=> {
return (
<div key={event.id}>
{new Date(event.date) > new Date() ?
<MarginalEvent title={event.title} summary={event.summary} date={format(new Date(event.date), 'dd MMMM, yyyy')} location={event.location} image={event.photo.childImageSharp.fluid} slug={event.slug} />
:
''
}
</div> )
})}
</div>
</div>
</Layout>
)
}
export default Events
What I have tried:
I tried to use:
useEffect(()=> {
const someref = interval.current
startTimer()
return ()=> {
clearInterval(someref)
}
}, [])
Or even this
useEffect(()=> {
const someref = interval.current
startTimer()
return ()=> {
clearInterval(someref)
}
}, [startTimer])
But it always gives another error message, I even used
useCallback()
but once again, it comes back with another issue. Can someone help me here?