Skip to main content

Accessing CloudBase MySQL Cloud Database in React Applications

Learning how to create a CloudBase MySQL data model, add sample data, and query data from a React application.

1. Create MySQL Data Model and Add Data

Create a data model named todos in the Cloud Development Console with the following field information:

Field NameField IDData TypeRequiredUnique
Is Completedis_completedBooleanNoNo
DescriptiondescriptionText, Multiline TextNoNo
TitletitleText, Single Line TextNoNo

After creation, enter sample data in the todos data model.

2. Create 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 CloudBase Environment Variables

Create a .env.local file and fill in your 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 cachedApp = null;

const getModels = async () => {
if (!cachedApp) {
cachedApp = cloudbase.init({
env: import.meta.env.VITE_CLOUDBASE_ENV_ID,
});
const auth = cachedApp.auth({
persistence: "local",
});
await auth.signInAnonymously();
}
return cachedApp.models;
};

function App() {
const [todos, setTodos] = useState([]);

useEffect(() => {
fetchTodos();
}, []);

const fetchTodos = async () => {
try {
const models = await getModels();
const { data } = await models.todos.list({
filter: { where: {} },
pageSize: 10,
pageNumber: 1,
getCount: true,
envType: "pre",
});
setTodos(data.records);
} catch (error) {
console.error("Failed to get todos:", error);
}
};

return (
<>
<div>
<ul>
{todos.map((todo) => (
<li key={todo._id}>{todo.title}</li>
))}
</ul>
</div>
</>
);
}

export default App;

6. Start the Application

Execute the following command in the project root directory to start the application:

npm run dev

Notes

  • When operating on data from different environments, you need to set the corresponding envType.
  • If using other login methods (refer to Authentication), replace auth.signInAnonymously() with the corresponding login method.