electron-userland / electron-json-storage

:package: Easily write and read user settings in Electron apps
1.43k stars 79 forks source link

Correct way of using electron-json-storage from renderer process #127

Closed vikdotdev closed 5 years ago

vikdotdev commented 5 years ago

When I use storage inside renderer process to write data on unload event. It works about 50% of the time, another outcome is that it produces file that looks like this data.json.2866685502.

When renamed without numbers the data inside is intact. On app restart the data obviously won't load. It looks like something locks the file and I have no idea what could cause that. storage is not used anywhere else except the code below.

Am I implementing it the right way ? What can cause the file to be locked? I'm new to electron and distributed software so I apologize if that's something obvious :)

renderer.js

DownloadData.retrieve().then(i => currentInstance = i);

window.addEventListener('unload', () => {
  if ( currentInstance ) {
    DownloadData.store(currentInstance);
  }
})

downloadData class methods:

  static retrieve () {
    return new Promise((resolve) => {
      storage.has('data', (err, hasKey) => {
        if (hasKey) {
          storage.get('data', (err, data) => {
            const instance = new DownloadData({ data })
            resolve(instance);
          });
        } else resolve( null );
      });
    });
  }

  static store (currentInstance) {
    storage.set('data', currentInstance, err => {
      if (err) throw err;
    });
  }

I'm on win10, electron-json-storage version 4.1.6

vikdotdev commented 5 years ago

I figured it out. I simply needed to make store method return a promise and close on promise resolve.

jviotti commented 5 years ago

I'm glad you figured it out! Let us know if you still need any help