electron-store icon indicating copy to clipboard operation
electron-store copied to clipboard

Docs missing how to deal with defaults for properties of an object (in schema)

Open binaryfunt opened this issue 4 years ago • 4 comments

I figured this out but will post the issue and show the solution in reply

const Store = require('electron-store');

const schema = {
    foo: {
        type: 'number',
        default: 14
    },
    bar: {
        type: 'object',
        properties: {
            a: {
                type: 'number',
                default: 5
            }
        }
    }
}

const store = new Store({schema: schema});

console.log(store.get('foo'));
//=> 14
console.log(store.get('bar.a'));
//=> Cannot get property 'a' of undefined (I've paraphrased the error message)

binaryfunt avatar Feb 14 '20 21:02 binaryfunt

From https://github.com/sindresorhus/conf/issues/85#issuecomment-531651424 the solution is to add default: {} to bar:


bar: {
    type: 'object',
    properties: {
        a: {
            type: 'number',
            default: 5
        }
    },
    default: {}
}
console.log(store.get('bar.a'));
//=> 5

Perhaps README could be updated to show this?

binaryfunt avatar Feb 14 '20 21:02 binaryfunt

Thank you, @binaryfunt! Agreed, this is exactly what I was struggling with.

durasj avatar Mar 28 '20 14:03 durasj

Same problem here. Thanks for the help. :) 👍

borsTiHD avatar Jul 24 '20 07:07 borsTiHD

Gosh I've been debugging for 3 hours and here is the answer Thank you!

olsen4930824 avatar Dec 26 '20 23:12 olsen4930824