Thursday, 7 July 2022

Saving lottie object with methods into the state

I'm trying to save a Lottie object with methods for later use (another useEffect) into the state, but the state says it's null.

I would like to use the anim.playSegments method specified in the documentation.

Lottie documentation.

Update #1: Tried including anim into the dependency array and event listener for checking if the animation has loaded, but that didn't help and the application resulted in a cycle.

Animation now loads indefinitely

import React, { useEffect, useRef, useState } from 'react';
import { useColorMode } from '@chakra-ui/react';
import lottie from 'lottie-web';
import animationData from '../assets/json/sun-to-night'

const ColorMode = () => {
  const container = useRef(null)
  const [anim, setAnim] = useState(null)
  const { colorMode, toggleColorMode } = useColorMode()

  // Segments of the animation
  const midToEnd = [14, 28]
  const startToMid = [0, 14]

  useEffect(() => {
    setAnim(() => {
      const lot = lottie.loadAnimation({
        container: container.current,
        animationData: animationData,
        autoplay: false,
        loop: false,
        name: 'anim'
      })
      document.addEventListener('DOMLoaded', () => {
        document.removeEventListener('DOMLoaded')
      })
      return lot
    });
    console.log(`${JSON.stringify(anim)}`) //Throws null
    anim.playSegments(
      (colorMode === 'dark'
        ? startToMid
        : midToEnd), true
    )
  }, [, anim]);

  useEffect(() => {
    // anim object is null
    anim.playSegments(
      (colorMode === 'dark'
        ? startToMid
        : midToEnd), true
    )
  }, [colorMode]);

  return (
    <>
      <div>
          ref={container}
          onClick={toggleColorMode}
      </div>
    </>
  )
}

export default ColorMode;


from Saving lottie object with methods into the state

No comments:

Post a Comment