Accessing CloudBase Data Models in React Applications
Learn how to create CloudBase MySQL data models, add sample data, and query data from React applications.
1. Create a MySQL Data Model and Add Data
Create a data model named todos in the Cloud Development Platform, with the field information as follows:

| Field Name | Field Identifier | Data Type | Required | Unique |
|---|---|---|---|---|
| Completion Status | is_completed | Boolean | No | No |
| Description | description | Text, Multi-line text | No | No |
| Title | title | Text, Single-line text | No | No |
After creation, enter sample data in the todos data model.
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 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 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.