Hello I'm building a Electron + React + Node app.
I need to import data from my app-config.json file into both my server.js(contains server side logic) and my App.js file.
This is my project structure:
electron-react-app
-build
-dist
-public
--app-config.json
--server.js
--index.html
--electron.js
-src
--App.js
--index.js
---components
I need the data inside my app-config.json to be imported into my files so I can use said data into my variables.
I can easy do it on my server.js like so:
const express = require("express");
const path = require("path");
const http = require("http");
const { Server } = require("socket.io");
const cors = require("cors");
const { SerialPort } = require("serialport");
const axios = require("axios");
const _ = require("underscore");
const fs = require("fs");
const bodyParser = require("body-parser");
const shutdown = require("electron-shutdown-command");
const { app } = require("electron");
const newApp = express();
newApp.use(cors());
const server = http.createServer(newApp);
const appConfigFile = require("./app-config.json");
let clientPort = appConfigFile.clientPort;
let serverIP = appConfigFile.serverIP;
let serverPort = appConfigFile.serverPort;
But on my App.js I try to fetch my data before declaring my const socketio but the class AppConfig variables come as undefined and the io.connect() function is not properly executed.
import io from "socket.io-client";
export class AppConfig {
static serverIP;
static serverPort;
}
fetch("app-config.json")
.then((r) => r.json())
.then((data) => {
AppConfig.serverIP = data.serverIP;
AppConfig.serverPort = data.serverPort;
});
export const socketio = io.connect(`http://${AppConfig.serverIP}:${AppConfig.serverPort}`);
//these variables come as undefined
function App() {...}
export default App;
Would there be a way to render my App.js component only after the app-config.json data is fetched?
Ill also add my app-config.json here:
{
"serverIP": "localhost",
"serverPort": 5000,
"clientPort": 3000,
}
Any help would be greatly aprecciated.
Edit:
This is my index.js file, where my App.js is rendered.
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import { ThemeProvider } from "@material-tailwind/react";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<ThemeProvider>
<App />
</ThemeProvider>
);
export class AppConfig {
static serverIP;
static serverPort;
}
fetch("app-config.json")
.then((r) => r.json())
.then((data) => {
AppConfig.serverIP = data.serverIP;
AppConfig.serverPort = data.serverPort;
})
.then(() => {
io.connect(`http://${AppConfig.serverIP}:${AppConfig.serverPort}`);
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<ThemeProvider>
<App />
</ThemeProvider>
);
});