#How to send data from Main process to React Component?
60 messages · Page 1 of 1 (latest)
I can't paste here, it's too long, I can only send as a file or github link
okay
import { app, shell, BrowserWindow, ipcMain } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import { getActivePorts } from '../serialport'
function createWindow(): void {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 1800,
height: 900,
show: false,
backgroundColor: 'red',
backgroundMaterial: 'acrylic',
autoHideMenuBar: true,
...(process.platform === 'linux' ? { icon } : {}),
webPreferences: {
preload: join(__dirname, '../preload/index.js'),
sandbox: false
}
})
mainWindow.on('ready-to-show', () => {
mainWindow.show()
})
mainWindow.webContents.setWindowOpenHandler((details) => {
shell.openExternal(details.url)
return { action: 'deny' }
})
// HMR for renderer base on electron-vite cli.
// Load the remote URL for development or the local html file for production.
if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
} else {
mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
}
mainWindow.webContents.send('data', "Some data")
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
// Set app user model id for windows
electronApp.setAppUserModelId('com.electron')
// Default open or close DevTools by F12 in development
// and ignore CommandOrControl + R in production.
// see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
app.on('browser-window-created', (_, window) => {
optimizer.watchWindowShortcuts(window)
})
createWindow()
app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import { getActivePorts } from '../serialport'
function createWindow(): void {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 1800,
height: 900,
show: false,
backgroundColor: 'red',
backgroundMaterial: 'acrylic',
autoHideMenuBar: true,
...(process.platform === 'linux' ? { icon } : {}),
webPreferences: {
preload: join(__dirname, '../preload/index.js'),
sandbox: false
}
})
mainWindow.on('ready-to-show', () => {
mainWindow.show()
})
mainWindow.webContents.setWindowOpenHandler((details) => {
shell.openExternal(details.url)
return { action: 'deny' }
})
// HMR for renderer base on electron-vite cli.
// Load the remote URL for development or the local html file for production.
if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
} else {
mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
}
mainWindow.webContents.send('data', "Some data")
}```
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
// Set app user model id for windows
electronApp.setAppUserModelId('com.electron')
// Default open or close DevTools by F12 in development
// and ignore CommandOrControl + R in production.
// see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
app.on('browser-window-created', (_, window) => {
optimizer.watchWindowShortcuts(window)
})
createWindow()
app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
That's much better, thanks
Now it's preload.ts:
import { electronAPI } from '@electron-toolkit/preload'
// Custom APIs for renderer
const api = {
getData: (callback) => ipcRenderer.on('data', callback)
}
// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
try {
contextBridge.exposeInMainWorld('electron', electronAPI)
contextBridge.exposeInMainWorld('api', api)
} catch (error) {
console.error(error)
}
} else {
// @ts-ignore (define in dts)
window.electron = electronAPI
// @ts-ignore (define in dts)
window.api = api
}
Okay, why do you need this if (process.contextIsolated)?
it's actually prewritten electron-vite boilerplate thing
Ehh it looks bad
Yeah but thats not the point
What error do you have?
I can't get data that I send from main process in my React Component
import './App.css'
import Brand from './components/Brand'
import Controller from './components/Controller'
import Copyright from './components/Copyright'
import Log from './components/Log'
import Space from './components/Space'
import Title from './components/Title'
const App = (): JSX.Element => {
const [value, setValue] = useState<any>()
useEffect(()=>{
window.api.getData((event, value)=>setValue(event))
console.log(value)
},[])
return (
<div className="App">
<Brand name={'SHBCN Systems'} color={'white'} ></Brand>
<Title title='Rocket Tracking Software' color='white'></Title>
<Controller width={500} height={50} background='white'></Controller>
<div className="monitors">
<Space width={700} height={600} backgound='black'></Space>
<Log width={600} height={600} background='black'></Log>
</div>
<Copyright company='DBRV Software' color='gray'></Copyright>
</div>
)
}
export default App```
Let me guess, you think it doesn't work because the console log returns undefined?
Exactly
Move it outside the useEffect, just before the return and try again
The console.log I mean
Actually I did it before
And?
you mena like that:
import './App.css'
import Brand from './components/Brand'
import Controller from './components/Controller'
import Copyright from './components/Copyright'
import Log from './components/Log'
import Space from './components/Space'
import Title from './components/Title'
const App = (): JSX.Element => {
const [value, setValue] = useState<any>()
useEffect(()=>{
window.api.getData((event, value)=>setValue(value))
},[])
console.log(value)
return (
<div className="App">
<Brand name={'SHBCN Systems'} color={'white'} ></Brand>
<Title title='Rocket Tracking Software' color='white'></Title>
<Controller width={500} height={50} background='white'></Controller>
<div className="monitors">
<Space width={700} height={600} backgound='black'></Space>
<Log width={600} height={600} background='black'></Log>
</div>
<Copyright company='DBRV Software' color='gray'></Copyright>
</div>
)
}
export default App```
Yes
no it make no sense
What doesn't make sense?
I still get undefined as a value
Okay, you need to check several things
First make sure the send on main is, well, sent
Then check if you receive something in the getData callback, put a log before the setValue
Actually when I do:
import './App.css'
import Brand from './components/Brand'
import Controller from './components/Controller'
import Copyright from './components/Copyright'
import Log from './components/Log'
import Space from './components/Space'
import Title from './components/Title'
const App = (): JSX.Element => {
const [value, setValue] = useState<any>()
useEffect(()=>{
console.log(window.api.getData((event, value)=>setValue(value)))
},[])
console.log(value)
return (
<div className="App">
<Brand name={'SHBCN Systems'} color={'white'} ></Brand>
<Title title='Rocket Tracking Software' color='white'></Title>
<Controller width={500} height={50} background='white'></Controller>
<div className="monitors">
<Space width={700} height={600} backgound='black'></Space>
<Log width={600} height={600} background='black'></Log>
</div>
<Copyright company='DBRV Software' color='gray'></Copyright>
</div>
)
}
export default App```
I get Object
Object
invoke
:
ƒ ()
postMessage
:
ƒ ()
send
:
ƒ ()
sendSync
:
ƒ ()
sendTo
:
ƒ ()
sendToHost
:
ƒ ()
_events
:
{data: Array(4)}
_eventsCount
:
1
_maxListeners
:
undefined
Symbol(kCapture)
:
false
[[Prototype]]
:
Object
What it supposed to show?
So it means the send doesn't work
You send message before listener is ready and registered
You mean, I have to call it inside app.whenReady block?
No
So how to fix it?
I think what you want is invoke/handle instead of on/send in this case
In your main file, inside electron options, change the preload value to index.ts, not js