0

I'm using react in electron trying to receive data from the main process to my renderer using the steps outlined here. https://www.electronjs.org/docs/latest/api/context-bridge

import React, { useState, useEffect } from "react";
import { channels } from "../../shared/constants";
const { api } = window;

const ScanRegion = () => {
  const [video, setVideo] = useState({});
  const [displaySources, setDisplaySources] = useState([]);

  console.log("test", api);

  useEffect(() => {
    api.receive(channels.GET_DATA, (data) => {
      console.log(data);
      setDisplaySources(data);
    });
  }, [displaySources]);

dev-tools-error

It seems like my renderer is picking up the function from the preload script's contextBridge, and then for some reason the window object is getting overwritten when react reloads, and I no longer have access to the receive function.

I haven't seen anyone else with this issue so maybe it's a really simple fix, here the rest of the related files.

preload:

const { contextBridge, ipcRenderer } = require("electron");

contextBridge.exposeInMainWorld("api", {
  receive: (channel, func) => {
    ipcRenderer.on(channel, (event, ...args) => func(...args));
  },
});

main:

function createWindow() {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, "preload.js"),
    },
  });

  win.loadURL("http://localhost:3000");

  win.webContents.openDevTools();
}

package.json:

"dependencies": {
    "bootstrap": "^5.3.1",
    "electron": "^22.2.1",
    "react": "^18.2.0",
    "react-bootstrap": "^2.8.0",
    "react-dom": "^18.2.0",
    "react-scripts": "4.0.3"
  },

edit: I'm fairly certain this post has the same issue as me but his question was never answered as well.

0 Answers0