'Electron + React keeps reload the page when fs.writeFileSync()
preload.js
const { readFile, readFileSync, writeFileSync } = require('fs')
const { contextBridge, ipcRenderer, ipcMain } = require('electron')
require('electron')
contextBridge.exposeInMainWorld('config', {
readConfig: () => {
const data = readFileSync(__dirname + '/config.json', 'utf-8')
return data
},
writeJson: (data) => {
writeFileSync(__dirname + '/config.json', data)
},
ipc: ipcRenderer,
})
React App.js
the function that causes Electron refresh
const onNoteAdd = () => {
const newNote = {
description: '',
id: Noteid,
}
const newArr = arr.concat(newNote)
writeJson(JSON.stringify(newArr))
setArr(newArr)
setNoteId((Noteid) => Noteid + 1)
}
Electron.js
app.on('ready', () => {
createWindow()
const ipc = ipcMain
ipc.on('message', (event, data) => {
console.log(data)
fs.writeFileSync(__dirname + '/config.json', data)
})
})
I want to overwrite the JSON in the public folder with the one that ipcMain received from the ipcRender in App.js
But the problem is that when writeFileSync works,
somehow electron gets refreshed and overwritting is skipped
I tried to overwrite with 'writeJson' function in preload.js file with App.js and using ipc.send in App.js and receive in Electron.js and write the json, but nothing worked.
Electron version is 12.0.7
Solution 1:[1]
you probably have hot reload enabled, try add an ignore path
electron-reloader
require('electron-reloader')(module, {ignore: [regex_to_config_json]})
electron-reload
require('electron-reload')(__dirname, {ignored: [regex_to_config_json] })
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | aptx |
