-
Notifications
You must be signed in to change notification settings - Fork 0
Closed
Description
Goal
Provide developers more insights to storage events (such as when the store has been initialized and is ready to accept write requests).
Note
- Existing classes renamed
StorageModel → EngineandStorageMethod → Connectorfor clarity. - While the
Schemaclass is not necessary for this feature, it does help to explain the relationship between application code and the data.
%%{init: {
"er": {
"layoutDirection": "LR",
"themeCSS": "[id^=entity-SCHEMA] { opacity: 50% }"
}
}}%%
erDiagram
SCHEMA {
string name
object fields
}
ENGINE {
string namespace
}
CONNECTOR {
object storageEngine
object schemas
}
SCHEMA ||--o{ CONNECTOR : "validates data for"
ENGINE ||--o{ CONNECTOR : "interacts with"
SCHEMA ||--|| ENGINE : "defines structure for"
1. Instantiate Schema, Engine, and Connector
This snippet shows how to set up a schema, instantiate a storage engine, and initialize a connector.
// Define a Schema for "User" data
const userSchema = new Schema('User', {
id: { type: 'number', required: true, primaryKey: true },
name: { type: 'string', required: true },
email: { type: 'string', required: false }
});
// Instantiate a storage engine (LocalStorage or IndexedDB)
const storageEngine = new IndexedDbStorageEngine('my-app');
// Instantiate a connector, providing the storage engine and schema
const connector = new IndexedDBConnector(storageEngine);
connector. initialize();2. Set Up Listener for User Creation
Attach an event listener to the connector to detect when a new User is created.
// Listen for "create" events from the connector
connector.on('create', (event) => {
if (event.schema === 'User') {
console.log('New User created:', event.data);
}
});
// Example: Creating a new user
connector.create(userSchema, { id: 1, name: 'Alice', email: '[email protected]' });3. Set Up React Hook to Listen for User Updates
This custom React Hook listens for user updates and updates state accordingly.
import { useEffect, useState } from 'react';
function useUserUpdates(connector) {
const [updatedUser, setUpdatedUser] = useState(null);
useEffect(() => {
const handleUpdate = (event) => {
if (event.schema === 'User') {
setUpdatedUser(event.data);
}
};
connector.on('update', handleUpdate);
return () => connector.off('update', handleUpdate);
}, [connector]);
return updatedUser;
}
// Usage inside a React component
function UserUpdateListener({ connector }) {
const latestUser = useUserUpdates(connector);
return (
<div>
{latestUser ? (
<p>Updated user: {latestUser.name}</p>
) : (
<p>Waiting for user updates...</p>
)}
</div>
);
}Metadata
Metadata
Assignees
Labels
No labels