cubing / cubing.js

🛠 A library for displaying and working with twisty puzzles. Also currently home to the code for Twizzle.
https://js.cubing.net/cubing/
GNU General Public License v3.0
232 stars 42 forks source link

Nextjs experimentalAddMove applies move twice #313

Closed chrisgloom closed 5 months ago

chrisgloom commented 5 months ago

Steps to reproduce the issue

sorry for the messy code had commented out a lot to challenge my assumptions.

Using experimentalAddMove in a react component in a nextjs project, the move happens twice for some reason, F is F2, R is R2...not sure why. Open to it being entirely my fault haha. Maybe something to do with it being in a react component?

const Twisty = ({ algString, latestMove }) => {
  console.log(algString)
  const twistyPlayerRef: TwistyPlayer = useRef<TwistyPlayer>(null)

  if (twistyPlayerRef.current && latestMove) {
    // testing adding a move
    twistyPlayerRef.current.experimentalAddMove('F')
  }

  useEffect(() => {
    // Accessing the twisty-player instance through ref
    if (twistyPlayerRef.current) {
      //   window.cube = twistyPlayerRef.current
      // Perform actions on the twisty-player instance
      twistyPlayerRef.current.experimentalModel.playingInfo.set({
        playing: true,
        loop: false,
      })
      demoSpinCamera(twistyPlayerRef.current, 0.5)
      // console.log()
    }
  }, [])
  // todo: only pass in new moves after the initial setup alg

  return (
    <>
      <twisty-player
        control-panel="bottom-row"
        background="none"
        ref={twistyPlayerRef}
        // experimental-setup-alg={algString}
      ></twisty-player>
    </>
  )
}

Observed behaviour

The intended move is applied twice to the cube

🖼 Screenshots

image

Expected behaviour

Just applied once

Environment

nextjs blog project

Additional info

No response

chrisgloom commented 5 months ago

hmm, attaching it to the window and calling the function in the console just does the move once as expected. These are some react shenanigans it seems. But I'm still confused, if my react code is being called twice, I'd expect to see any console log twice and I only get it once.

chrisgloom commented 5 months ago

Ah. Probably my react noob showing through, since it touches the DOM it needs to be done inside of useEffect otherwise react will do react things and rerender it I guess. Still not sure why I don't see two console logs but it's working now and I don't care enough to find out ;)

lgarron commented 5 months ago

Glad to hear you figured it out!