Hi all!
Little disclaimer: I am an embedded software engineer and web development is not my daily business, so my questions may be silly. Please be patient with me. :)
I am working through the Blockly guides and came across the Serialization topic, i.e. how to store and load the Blockly workspace.
```
// Serialize the state.
const state = Blockly.serialization.workspaces.save(myWorkspace);
// Then you save the state, e.g. to local storage.
localStorage.setItem('workspace-state', state);
```
+
```
// Get your saved state from somewhere, e.g. local storage.
const state = localStorage.getItem('workspace-state');
// Deserialize the state.
Blockly.serialization.workspaces.load(state, myWorkspace);
```
When I execute the store operation (I've added a "store" and a "load" button and two event listeners for clicking them), my browser throws an exception:
> Uncaught TypeError: can't convert state to string
Storing and directly re-loading works:
const state = Blockly.serialization.workspaces.save(workspace);
Blockly.serialization.workspaces.load(state, workspace);
```
So, it really seems that `localStorage.setItem('workspace-state', ...)` is already expecting something that can (implicitely?) be converted to a string. `state` seems to be an Object. So I tried the following workaround, which seems to work for me: use a pair of `JSON.stringify()` + `JSON.parse()`:
My whole snippet:
```
// Save program upon request
const saveBtn = document.getElementById('saveBtn');
saveBtn.addEventListener('click', () => {
if(workspace) {
// Serialize the state.
const state = Blockly.serialization.workspaces.save(workspace);
// Then you save the state, e.g. to local storage.
localStorage.setItem('workspace-state', JSON.stringify(state));
}
});
// Load program upon request
const loadBtn = document.getElementById('loadBtn');
loadBtn.addEventListener('click', () => {
if(workspace) {
// Get your saved state from somewhere, e.g. local storage.
const state = JSON.parse(localStorage.getItem('workspace-state'));
// Deserialize the state.
Blockly.serialization.workspaces.load(state, workspace);
}
});
```
Please let me know if I am missing something - or maybe the guide hasn't been updated after some interface changes?
Side note: I a have added custom blocks - could this be an issue with the default serialization? (I'd guess no.)
Cheers
Mäh