I'm building a React/Electron/MySQL app and am trying to pass the results of my query (in ipcMain) back to the renderer. Here is the basic skeleton:
main.js
ipcMain.handle("testQuery", async (event) => {
connection.connect(function(err) {
if(err){throw(err)}
let sql = "SELECT * FROM `workers`";
connection.query(sql, function(err, rows, fields) {
if(err){console.log(err); return}
console.log("results =", rows);
connection.end(function(){})
return rows; // i know this isn't currently returning anywhere useful
})
})
})
preload.js
contextBridge.exposeInMainWorld("electronAPI", {
testQuery: () => ipcRenderer.invoke("testQuery").then((result) => {return result})
})
MyComponent.jsx
async function testQuery() {
return await window.electronAPI.testQuery()
}
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {data : "nothing"}
}
render() {
return (
<button type="button" id="testButton" onClick={() =>
testQuery((result) => {
this.setState({data : result})
})}>Test Query</button>
<p>{this.state.data}</p>
)
}
}
I've tried some approaches found in other threads, like passing a callback through (which didn't work, somewhere the callback got lost). I've also received errors like "object could not be cloned" after getting creative moving things around. If I try to declare a variable in the top scope of ipcMain, and pass the query result to it before passing it back as the "invoke" reply, I get "Cannot enqueue Query after invoking quit." What approach should I be aiming towards? (I'm new to working with Promises, as well.)