Returning result from Electron to React

Viewed 87

I have an electron method to print:

ipcMain.on('print', (results, total) => {
    PosPrinter.print(print_data, {
      printerName: 'RECEIPT',
      preview: false,
      width: '170px',               //  width of content body
      margin: '15 15 15 15',            // margin of content body
      copies: 1,                   
      silent : true
  })
  .then(() => {
    // some code ...
    console.log("done");
    return "Printing successful.."
  })
  .catch((error) => {
    console.error(error);
    return "Something went wrong."
});

I am accessing this method on the react side like:

  handlePrint = (e) => {
    e.preventDefault();
    ipcRenderer.send('print', this.state.cheques, this.state.total);
  }

How would I be able to return the status message if the printing is successful or if there is an error to the renderer?

1 Answers

You must use event.reply() function from ipcMain.on()

Example with your code.

Main process. Electron

ipcMain.on('print', (event, results, total) => {
// some code

.then(() => {
 // some code ...
 event.reply('print', 'Printing successful..')

}).catch((error) => {
 event.reply('print', 'Something went wrong.')
});

Renderer Process (web page). React

ipcRenderer.on('print', (event, arg) => {
  console.log(arg) // prints "Printing successful.." or "Something went wrong."
})

You can allocate the render process code in the componentDidMount() or useEffect() of your component or your App.js

This is the way to transfer data from Main Process to Render Process in execute time as return function.

https://www.electronjs.org/docs/api/ipc-main#sending-messages

Related