How to handle plugin data change by another user? (private data stored by setPluginData)

Hello!
Could you please clarify these questions?
I want to store my private plugin data and let users of the file listen for update events of that data. So, if userA changed some data, userB should handle this event and refresh own UI. I’m trying to use setPluginData and figma.on, but I faced with problems:

  1. On which node should I call setPluginData? Plugin’s container? If so, how can I access it? I found a node associated with my plugin in the Developers tools, but this node doesn’t have the pluginId from my manifest.json.
  2. Suppose I successfully stored my plugin’s data in a node. How I can handle data change event? Can I use this code? And which property I need to parse?
figma.on('documentchange', (event) => {
  for (const change of event.documentChanges) {
    switch (change.type) {
      case "PROPERTY_CHANGE":
        for (const prop of change.properties) {
           // handle changed prop
        }
        break;
    }
  }
});

Hey Maxim! Welcome!

  1. you’ll want to setPluginData on figma nodes in the file. there is no plugin node. depending on what you are doing, that might be something like a relevant frame node. folks often store “general” information on the file root (figma.root). you can access this with getPluginData
  2. you can detect this PROPERTY_CHANGE with that snippet and change.properties.includes("pluginData")

together, you could do something like this…

setting data

figma.root.setPluginData("maxim", "wow!");

detecting the change

figma.on("documentchange", (event) => {
  const rootPluginDataChange = event.documentChanges.find((change) =>
    change.node.id === figma.root.id && 
    change.type === "PROPERTY_CHANGE" &&
    change.properties.includes("pluginData")
  )
  if (rootPluginDataChange) {
    const pluginDataValue = figma.root.getPluginData("maxim");
    respondToChange(pluginDataValue);
  }
})
3 Likes

Hello, Jake!
I modeled a case with two users, and it works!
Thank you very much for the detailed answer!

2 Likes

It’s probably worth mentioning that there is no way to detect which pluginData value specifically has changed without keeping track locally.

For example,

figma.root.setPluginData("maxim", "wow!");
figma.root.setPluginData("jake", "wow!");

would both be documentchange events on pluginData

if you were only interested in responding "maxim" changes, you will have to check the “maxim” value locally and see that the value different than the last time you checked.

using the code in my last post, the “respondToChange” handler would look something like this…

let lastMaximValue;

function  respondToChange(pluginDataValue) {
  if (pluginDataValue !== lastMaximValue) {
    lastMaximValue = pluginDataValue;
    console.log("ok the value we are watching actually changed!");
  }
}
2 Likes