craft.js icon indicating copy to clipboard operation
craft.js copied to clipboard

Canvas not preserving state

Open tonychandesign opened this issue 3 years ago • 3 comments

Describe the bug variable states aren't updating within element and canvas nodes. Cannot dynamically render different canvases using the hidden prop depending on variables states.

Screenshots Screen Shot 2020-08-05 at 11 48 28 AM

Additional context I've attached a video gif to showcase the output of the code. the state of variables change when their outside of the element node ezgif com-video-to-gif

Your environment

Software Version(s)
craft.js latest
React 16.10.2
Browser chrome
Operating System mac

tonychandesign avatar Aug 05 '20 18:08 tonychandesign

I'm encountering the same issue. Has anyone found a workaround for this?

donalffons avatar Oct 11 '21 19:10 donalffons

This is an expected behaviour for now. When you render a User Component (ie: <Element is={...} />), the props of that component is managed by its corresponding Node. So here's a simpler example:

const Example = () => {
  const [count, setCount] = useState(0);

  return <div><Element id="container" is={Text} text={count} /></div>
)

In this case, the Text component, once created, its values will be managed by its Node. So any subsequent changes to the count state will not propagate to the Text component. This is because we want a single source of truth, which should be Craft's EditorState.

So the only way would be to mutate the Node itself:

const { id } = useNode();
const { query, actions } = useEditor();

useEffect(() => {
   const node = query.node(id).get();
   if ( !node ) {
       return;
   }

   const textNodeId = node.data.linkedNodes.container; // container is the `id` of the linked Node (<Element id="container" />)
   actions.setProp(textNodeId, props => props.text = count);
}, [count]);

prevwong avatar Nov 06 '21 08:11 prevwong

Thanks a lot for the clarification. I had already realized that I was just using the library in the wrong way. I'm just starting with a bit of a deeper dive into craft.js right now and your explanation comes in very handy. Thanks again!

donalffons avatar Nov 09 '21 22:11 donalffons