#How to send data from Main process to React Component?

60 messages · Page 1 of 1 (latest)

solar surge
#

can you share the code instead of photos of the code?

solar surge
#

??

#

I mean paste the code here, on Discord

civic leaf
solar surge
#

it's not too long if you break it into multiple messages

#

only share what's revelant

civic leaf
#

okay

civic leaf
# solar surge only share what's revelant

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.

GitHub

Toolkit for Electron. Contribute to alex8088/electron-toolkit development by creating an account on GitHub.

solar surge
#

ehhh use the code tags please
```js
Your code
```

#

It will look like this:

Your code
civic leaf
# solar surge It will look like this: ``` Your code ```
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.
solar surge
#

That's much better, thanks

civic leaf
#

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
}
solar surge
#

Okay, why do you need this if (process.contextIsolated)?

civic leaf
solar surge
#

Ehh it looks bad

civic leaf
solar surge
#

What error do you have?

civic leaf
#

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```
solar surge
#

Let me guess, you think it doesn't work because the console log returns undefined?

solar surge
#

Move it outside the useEffect, just before the return and try again

#

The console.log I mean

civic leaf
#

Actually I did it before

solar surge
#

And?

civic leaf
#

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```
solar surge
#

Yes

civic leaf
#

no it make no sense

solar surge
#

What doesn't make sense?

civic leaf
#

I still get undefined as a value

solar surge
#

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

civic leaf
#

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

solar surge
#

Don't log this

#

Log the value inside the callback

civic leaf
#

Yeah, I tried it too

#

But it shows nothing

rain bay
#

What it supposed to show?

solar surge
#

So it means the send doesn't work

rain bay
#

You send message before listener is ready and registered

solar surge
#

Yes that

#

Can't see well with the bad formatting

civic leaf
rain bay
#

No

civic leaf
#

So how to fix it?

rain bay
#

Send message when listener is ready

#

In your react code

solar surge
#

I think what you want is invoke/handle instead of on/send in this case

hexed tree
#

In your main file, inside electron options, change the preload value to index.ts, not js