I want to move the useState variable selectedValue once it’s defined in edit.js and import it into save.js. In edit. js the code looks like this
This is impossible and not how save components work.
A save component takes a set of block attributes, and generates static HTML to be saved in the database. It’s also used to validate block markup. The save component should always return the same HTML when given the same block attributes.
You cannot:
- use state
- make remote API requests
- use lifecycle hooks such as
useEffect
etc - use callbacks
- use interactive UI
If you want to move use state in the edit component, you have to save it in a block attribute.
A Major Mistake You Haven’t Noticed
const [selectedValue, setSelectedValue] = useState('vtalk');
Storing the vtalk
value via useState
might make sense, but the edit component is not persistent, it can and will be destroyed and recreated arbitrarily, in fact you should expect this!.
As this happens, it’s possible the edit components internal state might not survive, erasing the value, and it won’t persist between page refreshes either.
The solution to this is also to store it in a block attribute. Any local state should be considered temporary and purely used for building the UI.
TLDR: There is no reason to use state in any of the code you have provided, get/set an attribute instead.