Access CloudBase PostgreSQL Database from a React Application
Learn how to create a CloudBase PostgreSQL database table, add sample data, and query data from a React application.
1. Create a PostgreSQL Database Table and Add Data
Create a database table named todos on the Cloud Development platform with the following fields:
| Column Name | Description | Type | Required | Unique |
|---|---|---|---|---|
| id | Identifier | int | Yes | Yes |
| is_completed | Completed | boolean | No | No |
| description | Description | text | No | No |
| title | Title | varchar | No | No |
After creation, enter sample data into the todos database table.
2. Create a React Application
Requires Node.js version >= 20.19
npm create vite@latest todo -- --template react
3. Install CloudBase SDK Dependencies
In the project root directory, run the following command:
cd todo && npm install @cloudbase/js-sdk
4. Declare CloudBase Environment Variables
Create a .env.local file and enter the CloudBase environment ID:
VITE_CLOUDBASE_ENV_ID=<CloudBase Environment ID>
5. Query Data from the Application
Add the following code in app.jsx to query data:
import cloudbase from "@cloudbase/js-sdk";
import { useEffect, useState } from "react";
import "./App.css";
let db = null;
const getDB = async () => {
if (!db) {
const app = cloudbase.init({
env: import.meta.env.VITE_CLOUDBASE_ENV_ID,
});
const auth = app.auth({
persistence: "local",
});
await auth.signInAnonymously();
db = app.rdb();
}
return db;
};
function App() {
const [todos, setTodos] = useState([]);
useEffect(() => {
fetchTodos();
}, []);
const fetchTodos = async () => {
try {
const { data } = await getDB().from("todos").select("*").range(0, 9);
setTodos(data);
} catch (error) {
console.error("Failed to fetch todos:", error);
}
};
return (
<>
<div>
<ul>
{" "}
{todos.map((todo) => (
<li key={todo.id}> {todo.title} </li>
))}{" "}
</ul>{" "}
</div>{" "}
</>
);
}
export default App;
6. Start the Application
In the project root directory, run the following command to start the application:
npm run dev
Notes
- When operating on data in different environments, set the corresponding
envType. - If using other login methods (refer to Authentication), replace
auth.signInAnonymously()with the corresponding login method.