Sure! Let's break down each of your requirements and provide a step-by-step guide on how to implement them. This comprehensive guide will help you set up your Electron desktop app with React, Vite, ShadCN, Jotai, React Query, and SQLite. We'll cover state management with Jotai, database integration with Electron and SQLite, data fetching with React Query, creating custom hooks, and building UI components with ShadCN.
1. State Management with Jotai
User Authentication and Global School Year Management
Jotai is a minimalistic state management library for React that allows for atomic state management. It's perfect for managing global states like user authentication and school year selection.
Step-by-Step Implementation
1.1. Install Jotai
First, install Jotai in your React project:
npm install jotai
1.2. Set Up Atoms
Atoms are the basic units of state in Jotai.
Authentication Atom
// src/atoms/authAtom.js
import { atom } from 'jotai';
export const authAtom = atom(null); // null means no user is logged in
School Year Atom
// src/atoms/schoolYearAtom.js
import { atom } from 'jotai';
export const schoolYearAtom = atom(new Date().getFullYear()); // Default to current year
1.3. Use Atoms in Components
Wrap your app with the Provider from Jotai:
// src/main.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { Provider } from 'jotai';
ReactDOM.render(
<Provider>
<App />
</Provider>,
document.getElementById('root')
);
Using the Authentication Atom
In your login component:
// src/components/Login.jsx
import React, { useState } from 'react';
import { useAtom } from 'jotai';
import { authAtom } from '../atoms/authAtom';
const Login = () => {
const [user, setUser] = useAtom(authAtom);
const [credentials, setCredentials] = useState({ username: '', password: '' });
const handleLogin = async () => {
// Call your authentication API via IPC
const result = await window.api.login(credentials);
if (result.success) {
setUser(result.user);
} else {
// Handle error
}
};
return (
// Your Login Form
);
};
export default Login;
Using the School Year Atom
In components where you need the selected school year:
// src/components/SchoolYearSelector.jsx
import React from 'react';
import { useAtom } from 'jotai';
import { schoolYearAtom } from '../atoms/schoolYearAtom';
const SchoolYearSelector = () => {
const [schoolYear, setSchoolYear] = useAtom(schoolYearAtom);
const handleYearChange = (event) => {
setSchoolYear(event.target.value);
};
return (
<select value={schoolYear} onChange={handleYearChange}>
{/* Render school year options */}
</select>
);
};
export default SchoolYearSelector;
1.4. Persisting State
For persisting authentication state (e.g., after app restart), you can use libraries like jotai-persist or handle it manually by saving the state in localStorage.
// src/atoms/authAtom.js
import { atomWithStorage } from 'jotai/utils';
export const authAtom = atomWithStorage('auth', null);
2. Connecting SQLite with Electron and Setting Up IPC
Electron Main Process and Renderer Process Communication
In Electron, the main process controls system-level operations, while the renderer process runs the frontend code. IPC (Inter-Process Communication) bridges these two processes.
Step-by-Step Implementation
2.1. Setting Up SQLite in the Main Process
Install SQLite Package
In the main process, install the sqlite3 package or better yet, better-sqlite3 for synchronous operations:
npm install better-sqlite3
Initialize the Database
// main.js (Electron Main Process)
const { app, BrowserWindow, ipcMain } = require('electron');
const Database = require('better-sqlite3');
let db;
function createWindow() {
const win = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
},
});
win.loadURL('http://localhost:3000');
}
app.whenReady().then(() => {
db = new Database('library.db');
// Initialize tables here if they don't exist
createWindow();
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});
2.2. Setting Up Preload Script
The preload script runs in the renderer process but has access to Node.js APIs, making it a safe bridge for IPC.
// preload.js
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('api', {
login: (credentials) => ipcRenderer.invoke('login', credentials),
// Other APIs
});
2.3. Handling IPC in Main Process
// main.js
ipcMain.handle('login', async (event, credentials) => {
// Access the database and perform login logic
const { username, password } = credentials;
const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);
if (user && bcrypt.compareSync(password, user.password)) {
return { success: true, user: { id: user.id, username: user.username } };
} else {
return { success: false, error: 'Invalid credentials' };
}
});
2.4. Secure IPC Practices
- Do not expose
ipcRenderer directly to the renderer process.
- Use the contextBridge API to expose only necessary functions.
- Validate all incoming data in the main process to prevent injection attacks.
3. Setting Up React Query for Data Fetching
Why React Query?
React Query simplifies data fetching, caching, and updating your UI based on server state.
Step-by-Step Implementation
3.1. Install React Query
npm install @tanstack/react-query
3.2. Set Up Query Client
// src/main.jsx
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
const queryClient = new QueryClient();
ReactDOM.render(
<Provider>
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
</Provider>,
document.getElementById('root')
);
3.3. Create Data Fetching Functions
Define functions in your preload script that communicate with the main process.
// preload.js
contextBridge.exposeInMainWorld('api', {
fetchBooks: (schoolYear) => ipcRenderer.invoke('fetch-books', schoolYear),
// Other APIs
});
In the main process, handle these IPC calls.
// main.js
ipcMain.handle('fetch-books', (event, schoolYear) => {
const books = db.prepare('SELECT * FROM books WHERE school_year = ?').all(schoolYear);
return books;
});
3.4. Use React Query in Components
// src/components/BooksList.jsx
import React from 'react';
import { useQuery } from '@tanstack/react-query';
import { useAtom } from 'jotai';
import { schoolYearAtom } from '../atoms/schoolYearAtom';
const BooksList = () => {
const [schoolYear] = useAtom(schoolYearAtom);
const { data: books, isLoading, error } = useQuery(['books', schoolYear], () =>
window.api.fetchBooks(schoolYear)
);
if (isLoading) return 'Loading...';
if (error) return 'An error occurred';
return (
<div>
{books.map((book) => (
<div key={book.id}>{book.title}</div>
))}
</div>
);
};
3.5. Handling Mutations
For CRUD operations, use React Query's useMutation.
import { useMutation, useQueryClient } from '@tanstack/react-query';
const queryClient = useQueryClient();
const mutation = useMutation((newBook) => window.api.addBook(newBook), {
onSuccess: () => {
// Invalidate and refetch
queryClient.invalidateQueries(['books', schoolYear]);
},
});
4. Creating Custom Hooks for CRUD Operations
Custom hooks help encapsulate logic and make components cleaner.
Step-by-Step Implementation
4.1. Define Custom Hooks
useBooks.js
// src/hooks/useBooks.js
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useAtom } from 'jotai';
import { schoolYearAtom } from '../atoms/schoolYearAtom';
export const useBooks = () => {
const [schoolYear] = useAtom(schoolYearAtom);
const queryClient = useQueryClient();
const booksQuery = useQuery(['books', schoolYear], () =>
window.api.fetchBooks(schoolYear)
);
const addBookMutation = useMutation((newBook) => window.api.addBook(newBook), {
onSuccess: () => queryClient.invalidateQueries(['books', schoolYear]),
});
const editBookMutation = useMutation((updatedBook) => window.api.editBook(updatedBook), {
onSuccess: () => queryClient.invalidateQueries(['books', schoolYear]),
});
const deleteBookMutation = useMutation((bookId) => window.api.deleteBook(bookId), {
onSuccess: () => queryClient.invalidateQueries(['books', schoolYear]),
});
return { booksQuery, addBookMutation, editBookMutation, deleteBookMutation };
};
4.2. Use Custom Hooks in Components
// src/components/BooksPage.jsx
import React from 'react';
import { useBooks } from '../hooks/useBooks';
const BooksPage = () => {
const { booksQuery, addBookMutation, editBookMutation, deleteBookMutation } = useBooks();
// Use booksQuery.data, booksQuery.isLoading, etc.
return (
// Your component code
);
};
export default BooksPage;
5. Building UI Components with ShadCN
About ShadCN
ShadCN provides a collection of accessible and customizable components built with Radix UI and Tailwind CSS.
Step-by-Step Implementation
5.1. Set Up Tailwind CSS
If not already set up, install Tailwind CSS:
npm install tailwindcss postcss autoprefixer
npx tailwindcss init -p
Configure tailwind.config.js:
module.exports = {
content: ['./src/**/*.{js,jsx,ts,tsx}'],
theme: {
extend: {},
},
plugins: [],
};
Add Tailwind directives in your CSS:
/* src/index.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
5.2. Install ShadCN Components
Install necessary components:
npm install @radix-ui/react-dialog @radix-ui/react-dropdown-menu @radix-ui/react-tooltip
5.3. Create Reusable Components
Form Components
// src/components/ui/TextInput.jsx
import React from 'react';
const TextInput = ({ label, ...props }) => (
<div className="my-2">
<label className="block text-sm font-medium text-gray-700">{label}</label>
<input
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
{...props}
/>
</div>
);
export default TextInput;
Table Component
// src/components/ui/Table.jsx
import React from 'react';
const Table = ({ columns, data }) => (
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
{columns.map((col) => (
<th key={col} className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
{col}
</th>
))}
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{data.map((row, idx) => (
<tr key={idx}>
{columns.map((col) => (
<td key={col} className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{row[col]}
</td>
))}
</tr>
))}
</tbody>
</table>
);
export default Table;
Chart Component using Recharts
You can use a chart library like Recharts for statistics.
npm install recharts
// src/components/ui/Chart.jsx
import React from 'react';
import { PieChart, Pie, Tooltip } from 'recharts';
const Chart = ({ data }) => (
<PieChart width={400} height={400}>
<Pie dataKey="value" data={data} cx="50%" cy="50%" outerRadius={60} fill="#8884d8" label />
<Tooltip />
</PieChart>
);
export default Chart;
5.4. Implementing Components in Pages
// src/pages/StatisticsPage.jsx
import React from 'react';
import Chart from '../components/ui/Chart';
const data = [
{ name: 'Open Loans', value: 10 },
{ name: 'Completed Loans', value: 40 },
];
const StatisticsPage = () => (
<div>
<h1 className="text-2xl font-bold">Statistics</h1>
<Chart data={data} />
{/* Additional statistics */}
</div>
);
export default StatisticsPage;
6. Additional Considerations
6.1. Excel Import with xlsx
Install xlsx:
npm install xlsx
Implement Excel import functionality in the renderer process:
// src/components/ExcelImport.jsx
import React from 'react';
import * as XLSX from 'xlsx';
const ExcelImport = () => {
const handleFileUpload = (event) => {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = (evt) => {
const data = evt.target.result;
const workbook = XLSX.read(data, { type: 'binary' });
// Assuming the first sheet contains the data
const firstSheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[firstSheetName];
const jsonData = XLSX.utils.sheet_to_json(worksheet);
// Send jsonData to main process or handle it here
window.api.importStudents(jsonData);
};
reader.readAsBinaryString(file);
};
return <input type="file" accept=".xlsx, .xls" onChange={handleFileUpload} />;
};
export default ExcelImport;
Handle importStudents in the preload script and main process.
6.2. Password Hashing with bcrypt
Install bcrypt in the main process:
npm install bcryptjs
Use bcrypt to hash passwords when creating accounts and compare hashes during login.
// For hashing passwords
const bcrypt = require('bcryptjs');
const hashedPassword = bcrypt.hashSync(plainTextPassword, saltRounds);
Summary
By following this guide, you should have a solid foundation for building your Electron desktop app using React, Vite, ShadCN, Jotai, React Query, and SQLite. Here's what we've covered:
- State Management with Jotai: Managing authentication state and school year selection using atoms.
- Database Integration: Connecting SQLite with the Electron main process and setting up secure IPC channels.
- Data Fetching with React Query: Fetching and mutating data efficiently with caching and invalidation.
- Custom Hooks: Encapsulating CRUD logic for cleaner components.
- UI Components with ShadCN: Building a modern interface with reusable and accessible components.
- Additional Features: Implementing Excel import functionality and secure password handling.
Next Steps
- Implement Remaining CRUD Operations: Extend the custom hooks and IPC handlers to cover students, loans, and archives.
- Enhance Security: Ensure all user inputs are validated and sanitized in the main process.
- Optimize Performance: Profile the app to find any bottlenecks, especially in data-heavy operations.
- Testing: Write unit and integration tests for your components and IPC handlers.
- Deployment: Use tools like
electron-builder to package your app for distribution.
With this framework, you’ll be able to build a robust and efficient high school library management system tailored to the needs of the school director.