The CRUDMachine is a versatile tool for managing data with Create, Read, Update, and Delete operations. It also supports undo and redo functionalities if versioning is enabled. Below is a step-by-step guide on how to use the CRUDMachine, including examples and customization options.
-
Import the CRUDMachine:
First, import the
CRUDMachineand necessary types from the module.import { CRUDMachine } from "@bhaireshm/zstate"; import type { CRUDOptions } from "@bhaireshm/zstate";
-
Define Your Data Structure:
Define the structure of the data you want to manage. For example, if you are managing a list of users:
interface User { id: string; name: string; email: string; }
-
Set Up CRUD Options:
Create an options object to configure your
CRUDMachine. You can specify initial data, enable versioning, and define custom transitions.const options: CRUDOptions<User[]> = { initialData: [], enableVersioning: true, maxVersions: 10, transitions: { customAction: (context, event) => { // Custom transition logic return {}; }, }, };
-
Initialize the CRUDMachine:
Instantiate the
CRUDMachinewith the options defined.const userCRUD = new CRUDMachine(options);
-
Perform CRUD Operations:
Use the methods provided by the
CRUDMachineto manipulate your data.-
Create:
userCRUD.create([{ id: "1", name: "John Doe", email: "john@example.com" }]);
-
Read:
const user = userCRUD.read("0"); // Read the first user
-
Update:
userCRUD.update([{ id: "1", name: "John Smith", email: "john.smith@example.com" }]);
-
Delete:
userCRUD.delete("0"); // Delete the first user
-
-
Undo and Redo:
If versioning is enabled, you can undo and redo changes.
userCRUD.undo(); // Undo the last operation userCRUD.redo(); // Redo the last undone operation
-
Subscribe to State Changes:
You can subscribe to state changes to react to data updates.
const unsubscribe = userCRUD.subscribe((state) => { console.log("State updated:", state); }); // Call unsubscribe() when you no longer need to listen to updates
-
Access Version History:
Retrieve the version history if versioning is enabled.
const history = userCRUD.getVersionHistory(); console.log("Version History:", history);
-
Custom Transitions:
You can define custom transitions in the
transitionsoption to handle specific events. -
Versioning:
Enable versioning to keep track of changes and allow undo/redo operations.
-
Max Versions:
Limit the number of versions stored to manage memory usage.
By following these steps, you can effectively use the CRUDMachine to manage your application's data with flexibility and control.