IndexedDB error: IDBObjectStore Symbol could not be cloned
Asked Answered
C

2

7

I have a class where some properties shouldn't be stored to the indexedDB store. It works when I clone the object and remove the properties afterwards, however that solution I didn't like so much. I wondered if there is a solution where we just set a property somehow private, so when writing to the indexedDB store the property shouldn't be included.

I tried the following: I used a symbol in my class for a property and through get/set I modify the property, however when I try to store the object to the indexedDB store I get the following error: IndexedDB error: IDBObjectStore Symbol could not be cloned

Here is an example code:

var request = indexedDB.open('test', 2);

request.onerror = function(event) {
    // Handle errors.
};
request.onupgradeneeded = function(event) {
    var db = event.target.result;

    // Create an objectStore to hold information about our customers. We're
    // going to use "ssn" as our key path because it's guaranteed to be
    // unique.
    var objectStore = db.createObjectStore("customers", {
        keyPath: 'id'
    });

    var mystring = "Hello World"
    
    var myblob = new Blob([mystring], {
        type: 'text/plain'
    });
    var file = new File([myblob], 'test');

    var a = Symbol('a');
    var obj = {
        id: 'foo',
        b: a
    };
    obj[a] = file;
    objectStore.add(obj);

};
Cressida answered 25/1, 2021 at 12:22 Comment(0)
C
7

Objects that can be stored in IndexedDB must be serializable. The spec definition for this is:

https://html.spec.whatwg.org/multipage/structured-data.html#serializable-objects

Symbol values are explicitly called out in the algorithm steps as non-serializable.

You could exclude the property from serialization by making it non-enumerable, e.g.:

Object.defineProperty(obj, 'b', {value: a, enumerable: false});
Conduction answered 25/1, 2021 at 22:32 Comment(0)
A
0

To omit certain properties:

let's say you have an object x

let x = {}
// add properties including symbol to x
...
// now to get only some properties
let { unwanted1, unwanted2, ...wanted } = x;
// now `wanted` contains all properties except the unwanted ones!
// the amazing magic of destructuring!

So in sum to save only some properties, you just use destructuring to name the ones you don't want.

Armourer answered 3/12, 2023 at 16:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.