Accessing CloudBase MySQL Databases in React Applications
Learn how to create CloudBase MySQL database tables, add sample data, and query data from React applications.
1. Create a MySQL Database Table and Add Data
Create a database table named todos in the Cloud Development Platform, with the field information as follows:
| Column Name | Description | Type | Required | Unique |
|---|---|---|---|---|
| id | Identifier | int | Yes | Yes |
| is_completed | Completion Status | boolean | No | No |
| description | Description | text | No | No |
| title | Title | varchar | No | No |
After creation, enter sample data in the todos database table.
2. Create a React Application
Requires Node.js version >= 20.19
npm create vite@latest todo -- --template react
3. Install Cloud Development SDK Dependencies
Execute the following command in the project root directory:
cd todo && npm install @cloudbase/js-sdk
4. Declare Cloud Development Environment Variables
Create the .env.local file and fill in the Cloud Development Environment ID.
VITE_CLOUDBASE_ENV_ID=<CloudBase Environment ID>
5. Querying Data from the Application
In app.jsx, add the following code 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.mysql();
}
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 obtain todo items:", error);
}
};
return (
<>
<div>
<ul>
{" "}
{todos.map((todo) => (
<li key={todo.id}> {todo.title} </li>
))}{" "}
</ul>{" "}
</div>{" "}
</>
);
}
export default App;
6. Launch Application
Execute the following command in the project root directory to launch the application:
npm run dev
Notes
- When operating on different environment data, you must set the corresponding
envType. - If using other login methods (refer to Authentication), replace
auth.signInAnonymously()with the corresponding login method.