Simple JSON in-memory auto-persistent database for server and client.
Features
- Simple JS object, no extraneous API
- Auto-persisted using on-change
- Saves to a json file on server, and uses localStorage in browser
- Works in browser, with React or Preact, or without
Note: Uses ES6 features (Proxy), use only where browser/env supports it
Install
npm i undb
Usage
const undb = const db onChange =
API
undb
const undb = const db onChange =
-
db
Deeply observed JS object that triggers auto-save feature when modified -
onChange
[fn]
Called wheneverdb
changes -
options
-
path
[str]
Path to use for persistence. Should be a filename on server, or a "namespace" on client -
initial
[obj]
Initial database structure -
clear
[bool]
Deletes all localstorage items except current path -
debounce
[num]
DebounceonChange
-
before
[bool]
MakeonChange
fire before the value has been updated indb
-
read
[fn=>obj]
Intercept the read function. Must return a data object.fn
is the default read function -
write
[cb=>null]
Intercept the write function. Must callcb
-
onChange
[obj]
Options passed to on-change
-
link
const link = const state1Tuple = const state2Tuple = ;
const link = const state1 state2 = ;
const state1 onChange link = const state2 =
-
link
[fn]
Link 2 or more states. Changing one will change the other(s).-
@param {...[state, onChange]|initial}
Takes either the[state, onChange]
tuple or aninitial
object to create a new reactive state object from. -
@returns state[]
Returns an array corresponding to the input arguments, each item either being the input[state]
(from the tuple) or a newly created one.
-
Browser specific
connect
connect
[fn=>fn=>Component]
Connects theonChange
to a<Component>
so that it re-renders wheneveronChange
is fired
const connect = const ReactiveComponent = <Component>
useState
useState
[obj=>obj]
React State Hook alternative that updates whenstate
object is modified
const useState = const state =
createUseState
createUseState
[fn=>fn]
Create auseState
hook for existingstate
const createUseState = const state onChange = const useState =
Examples
Global persistent store
Note: Re-renders entire React App
-
store.js
const undb =const store onChange =exportsstore = storeexportsonChange = onChange -
components/App.js
const store =module<h1>Hello storename!</h1><input => -
main.js
const React =const onChange =const App =
Local volatile state
-
components/App.js
const undb =const connect =const state onChange =const App =<h1>Hello statename!</h1><input =>moduleexports = App -
main.js
const React =const App =React
React State Hook Alternative
-
components/App.js
const useState =const App =const state =return<button =>`You have pressed this button times`</button>