Skip to main content
Question

waitForTask + useSyncedState loop

  • February 23, 2023
  • 2 replies
  • 291 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

This topic has been closed for replies.

2 replies

Michael_Yong
Figmate
  • Figmate
  • 7 replies
  • February 23, 2023

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
  • Author
  • 1 reply
  • February 23, 2023

I understand !

Many thanks for the reply