Gutenberg get withState variable in save function

That is not how blocks work. If you want to save something, it must be a block attribute.

withState lets a function have internal state, so it’s useful if you want to add toggle controls to your blocks UI, but it should not be used to store things that need to be saved. So you might use it to help build the UI for a block, hold temporary things, anything that doesn’t need to be solved and can be eliminated. E.g. wether a panel is open or collapsed.

Further, if we ignore this, and try to use withState we run into several issues:

  • the state in the save function would not be the same state, so the value wouldn’t carry over
  • the information would be in the HTML, but because it isn’t a block attribute it would not be saved and the next time you opened the editor it would dissapear and need to be reset or the HTML would change
  • withState is meant to be used inside a React component, but the save method is intended for generating the final HTML to go in the database.

The fundamental problem here is that the LinkToggleControl is using local ephemeral state to store wether it’s toggled or not, when it should be using setAttributes instead.