examples/react/README.md
This is an example of a simple project using PGlite and it's React integration. It uses Vite, React and TypeScript.
This example demonstrates the usage of some of PGlite's React API: PGliteProvider, usePGlite, useLiveQuery.
On page load, a database is created with a single table. On pressing the button, a new row is inserted into the database. The useLiveQuery will watch for any changes and display the most recently inserted 5 rows.
You need node (at least version 18), pnpm and git installed.
Check node version
$ node --version
Sample output: v20.9.0
Check pnpm version
$ pnpm --version
Sample output: 9.15.3
Check git version
$ git --version
Sample output: git version 2.34.1
This example depends on PGlite packages released on npmjs.com, so you don't need to build the entire PGlite project in order to run the example.
PGlite's main repository$ git clone https://github.com/electric-sql/pglite
$ cd ./pglite/examples/react
$ pnpm i --ignore-workspace
This example is part of the pglite pnpm workspace, but for our needs, we do not need to install all dependencies in the workspace. Thus passing the --ignore-workspace flag.
$ pnpm dev
Sample output:
VITE v6.1.0 ready in 126 ms
➜ Local: http://localhost:5173/
➜ Network: use --host to expose
➜ press h + enter to show help
If you'd like to start from scratch, here is how you can reproduce this example, so you understand better how it was made:
pnpm create vite. Follow the steps, input the name of your project (eg pglite-vite-react-project), select React for framework, TypeScript as variant.Sample output:
$ pnpm create vite
.../19522a4053e-20b11 | +1 +
.../19522a4053e-20b11 | Progress: resolved 1, reused 1, downloaded 0, added 1, done
✔ Project name: … pglite-vite-react-project
✔ Select a framework: › React
✔ Select a variant: › TypeScript
Scaffolding project in /tmp/pglite-vite-react-project...
Done. Now run:
cd pglite-vite-react-project
pnpm install
pnpm run dev
$ cd pglite-vite-react-project
$ pnpm install
$ pnpm run dev
$ pnpm run dev
VITE v6.1.0 ready in 126 ms
➜ Local: http://localhost:5173/
➜ Network: use --host to expose
➜ press h + enter to show help
$ pnpm install @electric-sql/pglite @electric-sql/pglite-react
Packages: +2
++
Downloading @electric-sql/[email protected]: 9.99 MB/9.99 MB, done
Progress: resolved 224, reused 180, downloaded 2, added 2, done
dependencies:
+ @electric-sql/pglite 0.2.17
+ @electric-sql/pglite-react 0.2.17
You are ready start using PGlite's React API. Make sure to exclude pglite from dependency optimization using the optimizeDeps option inside vite.config.js.
Have a look at this project's App.tsx, MyPGliteComponent.tsx and MyPGliteItemsComponent.tsx to see how you can create a database and use PGlite React's integration and start modifying your project. Switch to the browser to see your changes.