As a web developer, I find that whenever I'm looking to try something new, I first see if there's a way that I can leverage my knowledge foundation to find similarities play into the learning experience. Electron allows for such a cross and some wonderful analogies to getting started with desktop application development.
State management
The overlap in using a store between React and Electron is a nice getter/setter model similar to most state management systems in React. By requiring the electron-store
, one can easily get going:
// electron main.js
const Store = require('electron-store');
const store = new Store({
defaults: {
groceryList: {
produce: ["apples", "carrots", "pears"]
}
}
});
ipcMain.handle('get-produce', () => {
return store.get('groceryList.produce');
});
// ui.jsx (React component)
function ProduceListComponent() {
const [produce, setProduce] = useState(null);
useEffect(() => {
window.electron.getProduce().then(setProduce);
}, []);
// ... use 'produce' as needed
The IPC as a REST API
Poking around at the tutorials, each is quick to get talking about the IPC. The IPC (Inter-Process Communication) is similar to an internal API within a web app. Where fetch
is the browser's way to make a request, electron.ipcRenderer.invoke
is how this would be exposed to the Electron app's UI. As can be seen, both are async and promise-based.
// Web API Request
const fetchPriceData = async () => {
const response = await fetch('/api/price');
return response.json();
};
// Electron IPC
const getPriceData = async () => {
return await window.electron.invoke('get-price');
};
Route Architecture
Similar to Node/Express, building a route for a web API is the equivalent to an IPC handler. HTTP methods are similar to the IPC channel names, and the request/response cycle is to the IPC invoke/return.
const express = require('express');
const app = express();
app.get('/api/price/:id', async (req, res) => {
try {
const productId = req.params.id;
const productData = await database.getPriceById(productId);
res.json(productData);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
const { ipcMain } = require('electron');
ipcMain.handle('get-product', async (event, productId) => {
try {
const productData = await database.getProductById(productId);
return productData;
} catch (error) {
throw error;
}
});
It's been a fun start with Electron, and I'm looking forward to tinkering around its extensive API for building desktop applications.
Top comments (0)