Text conversion missing in Serialization / Save and load guide?

63 views
Skip to first unread message

maeh w

unread,
May 1, 2024, 1:08:19 PM5/1/24
to Blockly
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.

In https://developers.google.com/blockly/guides/get-started/save-and-load there are the following two snippets for saving and loading:

```
// 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

Rioni

unread,
May 1, 2024, 8:41:17 PM5/1/24
to Blockly
Hi! This is expected, the save function returns an object, but localStorage can only store strings. So doing JSON.stringify and JSON.parse is the correct way of persisting the state
Reply all
Reply to author
Forward
0 new messages