Skip to main content
Question

waitForTask + useSyncedState loop

  • February 23, 2023
  • 2 replies
  • 283 views

Olivier_Coste

When I use the example in waitForTask doc the widget doesn’t stop rendering

const { widget } = figma
const { Text, useEffect, waitForTask, useSyncedState } = widget

function WaitForTaskExample() {
  const [textContent, setTextContent] = useSyncedState("text", "Initial")

  useEffect(() => {
    waitForTask(new Promise(resolve => {
      // Simulate async work
      setTimeout(() => {
        setTextContent("Final")

        // Resolve the task
        resolve()
      }, 1000)
    }))
  })

  return <Text>{textContent}</Text>
}

widget.register(WaitForTaskExample)

On the setTextContent the widget seems to restart and rendering again and again

2 replies

Michael_Yong
Figmate

Ah, thanks for flagging this! This behavior is expected (and is a bug with our docs). Effects are run after we render the widget (which happens anytime a synced state / map value is updated). So in this particular code snippet:

  • Render widget
  • Effects run
  • Sets text context
  • Re-render widget
  • Effects run
  • Sets text context
  • Re-render widget

We’ll update the code sample to say:

      setTimeout(() => {
        if (textContent !== "Final") {
          setTextContent("Final")
        }

        // Resolve the task
        resolve()
      }, 1000)

Olivier_Coste

I understand !

Many thanks for the reply


Reply


Cookie policy

We use cookies to enhance and personalize your experience. If you accept you agree to our full cookie policy. Learn more about our cookies.

 
Cookie settings