I am trying to port a react XD plugin (UI Panel Hello React) to use functional react components. In the process, to achieve the same functionality as the setState callback function, I replaced it with a useEffect hook with that particular state as a dependency for useEffect.
This is the particular piece of code that needs changing.
color
is a piece of state.
colorChanged(color) {
this.setState({
color: {
r: color.r,
g: color.g,
b: color.b,
a: color.a
},
}, () => {
const { r, g, b, a } = this.state.color;
const { editDocument } = require("application");
const { selection, Color } = require("scenegraph");
editDocument({editLabel: "Change Colors"}, () => selection.items.forEach(item => item.fill = new Color(`rgba(${r}, ${g}, ${b}, ${a})`)));
}
);
}
Rewritten with hooks: color has been specified as a dependency for useEffect and a variable initialRender
is used to prevent firing this on the initial component mount.
const colorChanged = (color) => {
setcolor({r: color.r, g: color.g, b: color.b, a: color.a});
}
useEffect(() => {
const { r, g, b, a} = color;
const { editDocument } = require("application");
const { selection, Color } = require("scenegraph");
if (initialRender) {
editDocument({editLabel: "Change Colors"}, () => selection.items.forEach(item => item.fill = new Color(`rgba(${r}, ${g}, ${b}, ${a})`)));
}
initialRender = true;
}, [color]);
Error:
Plugin Error: Panel plugin edits must be initiated from a supported UI event