I am working on an Electron.js application and trying to pass a token from the main process to the renderer process using ipcMain and ipcRenderer. However, when I attempt to log the received data in the renderer, it logs undefined.
ipcMain.on(IPC_ACTIONS.RECEIVE_TOKEN, async (event) => {
if (mainWindow) {
try {
const response = await fetch("http://example.com/generate-token", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
});
const data: { token?: string } = await response.json();
console.log("API response in main process:", data);
correctly, e.g., { token: "your-token-here" }
if (data && data.token) {
event.reply(IPC_ACTIONS.RECEIVE_TOKEN, { token: data.token });
} else {
event.reply(IPC_ACTIONS.RECEIVE_TOKEN, { error: "Token not received from the server" });
}
} catch (error) {
console.error("Error during API call:", error);
event.reply(IPC_ACTIONS.RECEIVE_TOKEN, { error: error.message });
}
}
});
const ipcRenderer = (window as any).ipcRenderer;
const navigate = useNavigate();
ipcRenderer.on(IPC_ACTIONS.RECEIVE_TOKEN, (event: any, payload: any) => {
console.log("Full payload received from main process:", payload);
if (payload && payload.token) {
console.log("Token received in renderer:", payload.token);
} else if (payload && payload.error) {
console.error("Error received:", payload.error);
} else {
console.error("Unexpected response received from main process:", payload);
}
});
const handleButtonClick = () => {
ipcRenderer.send(IPC_ACTIONS.RECEIVE_TOKEN);
};
Even though the console.log(“API response in main process:”, data); in the main process prints a valid token (e.g., { token: “your-token-here” }), the console.log(“Full payload received from main process:”, payload); in the renderer process logs undefined