Storing data in electron
Tags: javascript, electronjs, localstorage, npm
Published: 2021-07-11 20:44:43

I created a lot of applications using electron, and the problems I faced were always with persisting data and user preferences.
I had to spend a lot of time and effort trying to save data to a JSON file and trying to update it every time the data changes in the app, so I said to my self why not creating a package that can help me do so.
I started writing the package and adding to it all the features I needed, so after some coding, testing, and debugging I come up with this package called [electron-data-holder](https://www.npmjs.com/package/electron-data-holder). BTW it was very difficult to find this name because every name I try is already taken. Nowadays, finding a name for your package is harder than making the package itself.

This package has a lot of features such as:
- Creating multiple files each one with its name, for example, a file for storing data and another for storing user preferences.
- Encrypting the data
- Specify the folder where you want to put the JSON files
- The data is watched and the JSON files will be updated after every change
- There is no API to manipulate the data, work with your data as you would do in vanilla Javascript.

## How it works

### Step 1 :

In the main process call `initDB()`, this function accepts a configuration object with 2 properties:

- key : `string` `(not required)` : the encryption key must be 32 characters long
- customPath : `string` `(not required)` : The path to the folder where you want to store the JSON files.

```js
const { initDB } = require('electron-data-holder');

// the encryption key must be 32 characters long.

initDB({ key: 'the-encryption-key', customPath: 'the-path-to-the-folder' });

```

The 2 parameters are not required, if you didn't pass an encryption key the data won't be encrypted and if you didn't pass a folder path, the folder will be `app.getPath('userData')`.

### Step 2 :

In the rendrer call `storeDB()`, this function accepts 2 parameters :

- Data object : `object` `(required)` : The data must be an object.
- Configuration object : `(not required)` : accepts 2 properties :
  - fileName : `string`: The name is a string and without the `.json` part the default is `data.json`.
  - encryption : `boolean` : whether you want the data to be encrypted or not, the default is ` false`.

```js
const { storeDB } = require('electron-data-holder');

// This function will returns a proxy with your data in it in order to watch the changes and update the JSON file.

const data = storeDB(
  {
    user: {
      firstName: 'Elon',
      lastName: 'Mask',
    },
    hobbies: ['learning', 'codding'],
  },

  {
    fileName: 'dataFile',
    encryption: true,
  }
);

// you can create multiple files by giving each one a different name

const config = storeDB(
  {
    darkMode: true,
    fontSize: 16,
    fontFamily: ['Courier', 'Courier', 'Everson Mono'],
  },

  { fileName: 'config' }
);
```

When the app is launched, it will search for the JSON files and get the data from them if they exist and return it, if not it will use the object you passed as the first parameter.

After writing these lines of code, you are now ready to work on your app without worrying about the data.

## Manipulating data

Let's use this example:

```js
const { storeDB } = require('electron-data-holder');

const data = storeDB(
  {
    user: {
      firstName: 'Elon',
      lastName: 'Mask',
    },
    hobbies: ['learning', 'coding'],
  },

  {
    fileName: 'dataFile',
    encryption: true,
  }
);
```

### Reading data

Let's log to the console the first element in the hobbies array:

```js
console.log(data.hobbies[0]); // 'learning'
```

### Modifying data

Let's add "gaming" to the hobbies array:

```js
data.hobbies.push('gaming');

console.log(data.hobbies); // Proxy {0: "learning", 1: "coding", 2: "gaming"}
```

Let's add an "age" property to the user object:

```js
data.user.age = 47;

console.log(data.user); // Proxy {firstName: "Elon", lastName: "Mask", age: 47}
```

The `storeDB()` function returns a proxy with your data in it in order to watch the changes and update the JSON file.
Every time you modify your data the JSON file will be updated accordingly.

As you can see there is no extra stuff for reading and modifying your data and also you don't need to worry about saving it in every change, this package will handle everything for you so you can focus on building your app. HAPPY CODING