1

I'm using react-odometerjs in Nextjs. As suggested by the doc:

import dynamic from 'next/dynamic'

const Odometer = dynamic(import('react-odometerjs'), {

  ssr: false,

  loading: () => <p>0</p>,

})


const App: FC = () => {
const [odometerValue, setOdometerValue] = useState<number>(0)

useEffect(() => {
    const Millisecond = 20000

    setOdometerValue(300)

    setInterval(function () {
      setOdometerValue(300)
    }, Millisecond)

    // }

  }, [])

return  <Odometer value={odometerValue} format='(,ddd)' animation='count' duration={1000} />

I import it with dynamic import but in this way the number don't animate and scroll when numbers change. I noticed that if I import it without dynamic import, I can see the number animate just before the next render when I get the error "document not defined".

Anyone else having this issue?

If anyone has suggestion for better/different solutions or packages, please share it. I searched a lot but cannot find a good alternative.

juliomalves
  • 42,130
  • 20
  • 150
  • 146
Giorgia Sambrotta
  • 1,133
  • 1
  • 15
  • 45

1 Answers1

0

The issue is not with the dynamic import but actually with the code inside the useEffect.

Try updating it to match the following:

useEffect(() => {
    setOdometerValue(300);
    const interval = setInterval(() => {
      setOdometerValue((value) => value + 300);
    }, 20000);
    return () => clearInterval(interval);
}, []);

You want to return a cleanup function from the useEffect when using window methods like setTimeout, setInterval, addEvenListener, etc.

juliomalves
  • 42,130
  • 20
  • 150
  • 146
  • 1
    Thank you! I did indeed implement the clearInterval after it but I didn't connect that it was the reasons why it woudl work. Make sense now! – Giorgia Sambrotta Jan 05 '21 at 13:12