Home > Software engineering >  Electron.js: How can I achieve a reactive variable update in the preload.js file?
Electron.js: How can I achieve a reactive variable update in the preload.js file?

Time:10-13

Let's say that I have the following code:

/* ** preload.js ** */
const {contextBridge} = require('electron');
const os = require('os');

contextBridge.exposeInMainWorld('system', {
   freeMemory: () => os.freemem()
});

How can I expose freeMemory every time this value changes?

I save this freeMemory value to the svelte store

/* ** store.js ** */
import {writable} from 'svelte/store';

export const freeMemory = writable(window.system.freeMemory());

I will use the freeMemory variable from svelte store in the svelte component as follows:

/* ** App.svelte ** */
<script>
   import {freeMemory} from 'store.js';
</script>

<main>
   Current available memory: { $freeMemory } bytes
</main>

This example works well. But the only thing that doesn't work properly is updating the freeMemory value in the svelte store in real time. Electron.js probably gets the value for the freeMemory variable only once and then does not update the value after that. Is there a way to update this value every time it changes in real time?

I code in electron.js for a short time.

CodePudding user response:

Memory changes pretty much all the time, so you can just update it in an interval. The way freeMemory is defined you should be able to just call it again:

export const freeMemory = writable(window.system.freeMemory());
setInterval(() => freeMemory.set(window.system.freeMemory()), 1000);

(Can be optimized to just export the subscribe function, as this should not be writable outside.)

  • Related