a promise based predictable state container
_Simple. Predictable. Promise-ful._
Stateful is a promise based predicate data store. It requires almost zero-setup and provides a simple API to interact with the created "Pools".
---
A pool is an object that can store any type of data as a key-value pair. For example, a pool named "Todos" can be created to store a list of Todos. A pool has access to a number of methods that are used to add, update or remove data from the pool. Every value in the pool must have a key even if the payload is empty.
---
Install using a package manager such as Yarn:
``shell`
yarn add @_agco/stateful
---
The library exposes simple APIs for data manipulation and management:
`js
// Modules
import { Pool } from "@_agco/stateful";
// Pools
const Todos = new Pool({ name: "Todos" });
`
This will create a Pool named "Todos" in the global state tree. Now we can utilize this pool to store and update data by using its prototypes:
---
- Returns the data in the pool.
- Accepts a parameter key which can be a string or an array of keys i.e. Array
- It returns a promise, and the successful response is the requested data.
`js
// Get all pool properties
Todos.get().then(state => {
// statements
});
// Get a specific property
Todos.get("todo1").then(state => {
// statements
});
// Get multiple properties
Todos.get(["todo1", "todo2", "todoN"]).then(state => {
// statements
});
`
---
- Adds or Updates the data in the pool.
- Accepts two parameters, a key and a payload.key
- The can be a string or an array of objects i.e. { key, payload }, where key is required.
- It returns a promise, and the successful response is the snapshot of the updated pool.
`js
// Add a property to the pool
Todos.update("amount", 1000).then(newstate => {
// statements
});
// Add multiple properties to the pool
Todos
.update([
{ key: "todo1", payload: "buy grocery" },
{ key: "todo2", payload: "dinner with mom" }
]).then(newstate => {
// statements
});
`
---
- Checks whether a property exists in the pool.
- It returns the value of the property if it exists, otherwise, returns false.
`js`
// Check if "todo1" exists in pool
Todos.has("todo1"); // returns {...} or false
---
- Removes one or more properties by passing the key as a parameter.
- It returns a promise, and the successful response is the snapshot of the updated pool.
`js
// Remove a specific property
Todos.remove("todo").then(newstate => {
// statements
});
// Remove multiple properties using regex
Todos.remove(/todo_i/).then(newstate => {
// statements
});
`
---
- Empties the pool
`js`
// Empty the pool
Todos.reset(); // returns {}
---
- Registers a callback which will be exectued whenever the pool is updated.
`js``
// assign a method to be called when the pool is updated.
Todos.subscribe(() => {
// statements
});