Installations
npm install unistore
Developer Guide
Typescript
No
Module System
CommonJS
Node Version
14.4.0
NPM Version
6.14.5
Score
93.6
Supply Chain
96.8
Quality
76
Maintenance
100
Vulnerability
100
License
Releases
Contributors
Unable to fetch Contributors
Languages
JavaScript (100%)
Developer
Download Statistics
Total Downloads
5,068,068
Last Day
928
Last Week
6,744
Last Month
54,732
Last Year
668,030
GitHub Statistics
2,857 Stars
226 Commits
139 Forks
40 Watching
4 Branches
34 Contributors
Bundle Size
722.00 B
Minified
402.00 B
Minified + Gzipped
Package Meta Information
Latest Version
3.5.2
Package Id
unistore@3.5.2
Size
17.15 kB
NPM Version
6.14.5
Node Version
14.4.0
Publised On
18 Jun 2020
Total Downloads
Cumulative downloads
Total Downloads
5,068,068
Last day
-51.2%
928
Compared to previous day
Last week
-44.4%
6,744
Compared to previous week
Last month
-21.9%
54,732
Compared to previous month
Last year
-8.2%
668,030
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
unistore
A tiny 350b centralized state container with component bindings for Preact & React.
- Small footprint complements Preact nicely (unistore + unistore/preact is ~650b)
- Familiar names and ideas from Redux-like libraries
- Useful data selectors to extract properties from state
- Portable actions can be moved into a common place and imported
- Functional actions are just reducers
- NEW: seamlessly run Unistore in a worker via Stockroom
Table of Contents
Install
This project uses node and npm. Go check them out if you don't have them locally installed.
1npm install --save unistore
Then with a module bundler like webpack or rollup, use as you would anything else:
1// The store: 2import createStore from 'unistore' 3 4// Preact integration 5import { Provider, connect } from 'unistore/preact' 6 7// React integration 8import { Provider, connect } from 'unistore/react'
Alternatively, you can import the "full" build for each, which includes both createStore
and the integration for your library of choice:
1import { createStore, Provider, connect } from 'unistore/full/preact'
The UMD build is also available on unpkg:
1<!-- just unistore(): --> 2<script src="https://unpkg.com/unistore/dist/unistore.umd.js"></script> 3<!-- for preact --> 4<script src="https://unpkg.com/unistore/full/preact.umd.js"></script> 5<!-- for react --> 6<script src="https://unpkg.com/unistore/full/react.umd.js"></script>
You can find the library on window.unistore
.
Usage
1import createStore from 'unistore' 2import { Provider, connect } from 'unistore/preact' 3 4let store = createStore({ count: 0, stuff: [] }) 5 6let actions = { 7 // Actions can just return a state update: 8 increment(state) { 9 // The returned object will be merged into the current state 10 return { count: state.count+1 } 11 }, 12 13 // The above example as an Arrow Function: 14 increment2: ({ count }) => ({ count: count+1 }), 15 16 // Actions receive current state as first parameter and any other params next 17 // See the "Increment by 10"-button below 18 incrementBy: ({ count }, incrementAmount) => { 19 return { count: count+incrementAmount } 20 }, 21} 22 23// If actions is a function, it gets passed the store: 24let actionFunctions = store => ({ 25 // Async actions can be pure async/promise functions: 26 async getStuff(state) { 27 const res = await fetch('/foo.json') 28 return { stuff: await res.json() } 29 }, 30 31 // ... or just actions that call store.setState() later: 32 clearOutStuff(state) { 33 setTimeout(() => { 34 store.setState({ stuff: [] }) // clear 'stuff' after 1 second 35 }, 1000) 36 } 37 38 // Remember that the state passed to the action function could be stale after 39 // doing async work, so use getState() instead: 40 async incrementAfterStuff(state) { 41 const res = await fetch('foo.json') 42 const resJson = await res.json() 43 // the variable 'state' above could now be old, 44 // better get a new one from the store 45 const upToDateState = store.getState() 46 47 return { 48 stuff: resJson, 49 count: upToDateState.count + resJson.length, 50 } 51 } 52}) 53 54// Connecting a react/preact component to get current state and to bind actions 55const App1 = connect('count', actions)( 56 ({ count, increment, incrementBy }) => ( 57 <div> 58 <p>Count: {count}</p> 59 <button onClick={increment}>Increment</button> 60 <button onClick={() => incrementBy(10)}>Increment by 10</button> 61 </div> 62 ) 63) 64 65// First argument to connect can also be a string, array or function while 66// second argument can be an object or a function. Here we pass an array and 67// a function. 68const App2 = connect(['count', 'stuff'], actionFunctions)( 69 ({ count, stuff, getStuff, clearOutStuff, incrementAfterStuff }) => ( 70 <div> 71 <p>Count: {count}</p> 72 <p>Stuff: 73 <ul>{stuff.map(s => ( 74 <li>{s.name}</li> 75 ))}</ul> 76 </p> 77 <button onClick={getStuff}>Get some stuff!</button> 78 <button onClick={clearOutStuff}>Remove all stuff!</button> 79 <button onClick={incrementAfterStuff}>Get and count stuff!</button> 80 </div> 81 ) 82) 83 84export const getApp1 = () => ( 85 <Provider store={store}> 86 <App1 /> 87 </Provider> 88) 89 90export const getApp2 = () => ( 91 <Provider store={store}> 92 <App2 /> 93 </Provider> 94)
Debug
Make sure to have Redux devtools extension previously installed.
1import createStore from 'unistore' 2import devtools from 'unistore/devtools' 3 4let initialState = { count: 0 }; 5let store = process.env.NODE_ENV === 'production' ? createStore(initialState) : devtools(createStore(initialState)); 6 7// ...
Examples
API
createStore
Creates a new store, which is a tiny evented state container.
Parameters
state
Object Optional initial state (optional, default{}
)
Examples
1let store = createStore(); 2store.subscribe( state => console.log(state) ); 3store.setState({ a: 'b' }); // logs { a: 'b' } 4store.setState({ c: 'd' }); // logs { a: 'b', c: 'd' }
Returns store
store
An observable state container, returned from createStore
action
Create a bound copy of the given action function.
The bound returned function invokes action() and persists the result back to the store.
If the return value of action
is a Promise, the resolved value will be used as state.
Parameters
action
Function An action of the formaction(state, ...args) -> stateUpdate
Returns Function boundAction()
setState
Apply a partial state object to the current state, invoking registered listeners.
Parameters
update
Object An object with properties to be merged into stateoverwrite
Boolean Iftrue
, update will replace state instead of being merged into it (optional, defaultfalse
)
subscribe
Register a listener function to be called whenever state is changed. Returns an unsubscribe()
function.
Parameters
listener
Function A function to call when state changes. Gets passed the new state.
Returns Function unsubscribe()
unsubscribe
Remove a previously-registered listener function.
Parameters
listener
Function The callback previously passed tosubscribe()
that should be removed.
getState
Retrieve the current state object.
Returns Object state
connect
Wire a component up to the store. Passes state as props, re-renders on change.
Parameters
mapStateToProps
(Function | Array | String) A function mapping of store state to prop values, or an array/CSV of properties to map.actions
(Function | Object)? Action functions (pure state mappings), or a factory returning them. Every action function gets current state as the first parameter and any other params next
Examples
1const Foo = connect('foo,bar')( ({ foo, bar }) => <div /> )
1const actions = { someAction } 2const Foo = connect('foo,bar', actions)( ({ foo, bar, someAction }) => <div /> )
Returns Component ConnectedComponent
Provider
Extends Component
Provider exposes a store (passed as props.store
) into context.
Generally, an entire application is wrapped in a single <Provider>
at the root.
Parameters
props
Objectprops.store
Store A {Store} instance to expose via context.
Reporting Issues
Found a problem? Want a new feature? First of all, see if your issue or idea has already been reported. If not, just open a new clear and descriptive issue.
License
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
Found 9/18 approved changesets -- score normalized to 5
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
license file not detected
Details
- Warn: project does not have a license file
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 21 are checked with a SAST tool
Score
3.3
/10
Last Scanned on 2025-01-06
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More