Security News
ESLint is Now Language-Agnostic: Linting JSON, Markdown, and Beyond
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
Mutastate is designed to manage state and send notifications to listeners when state changes.
npm install --save mutastate
importables
import Mutastate, {
withMutastateCreator,
} from 'mutastate';
The mutastate class, this class is responsible for maintaining state and sending notifications to listeners
import Mutastate from 'mutastate';
const mutastate = new Mutastate();
mutastate.set('foghorn', 'leghorn');
console.log(mutastate.get('foghorn')) // returns leghorn
Functions
getAgent(onChangeFunction)
getProxyAgent(onChangeFunction)
listen(key, listener = { callback: () => {}}, alias: null, batch: null, transform: null, defaultValue: undefined })
unlisten(key, callback)
unlistenBatch(batch, basePath)
getForListener(key, listener, keyChange)
get(key)
set(key, value, options)
delete(key)
assign(key, value)
push(key, value, options)
pop(key, options)
has(key)
getEverything()
setEverything(data)
addChangeHook(callback)
({ key: [], value: any, meta: { defaultValue: true|undefined, setEverything: true|undefined }}) => {}
this is most useful for automated persistence functionalityremoveChangeHook(callback)
replicate({ send, primary, ignore, sendInitial, canSetEverything })
functions
new MutastateAgent(mutastateInstance, callbackFunction)
or mutastateInstance.getAgent(callbackFunction)
listen(key, { alias, transform, initialLoad = true, defaultValue } = {})
callbackFunction
from the constructorlistenFlat(key, { alias, transform, initialLoad = true, defaultValue } = {})
batchListen(childFunction)
multiListen(listeners, { flat = true } = {})
get(key)
set(key, value)
delete(key)
assign(baseKey, value)
push(baseKey, value)
pop(key)
has(key)
assure(key, defaultValue)
has
fails on this key
, use set
at that key
with defaultValue
getEverything()
setEverything(data)
getAgentData()
pause()
resume()
resolve(aliasedKey)
agent.listen('a.b.c', { alias: 'bobby' });
then agent.resolve('bobby')
will return ['a', 'b', 'c']
You can use react hooks like so:
import React from 'react';
import { useMutastate } from 'mutastate';
const randomName = () => ['jerry', 'bobby', 'carl'][Math.floor(Math.random() * 3)];
function Assignment(props) {
[assignment, setAssignment] = useMutastate(['assignment', props.id]);
const updateAssignment = (data) => {
return setAssignment({ ...assignment, ...data });
}
return (
<div>
<div>{assignment.name}</div>
<div>{assignment.count}</div>
<div>{JSON.stringify(assignment.list)}</div>
<button onClick={() => updateAssignment({ count: assignment.count + 1 })}>Add To Count</button>
<button onClick={() => updateAssignment({ name: randomName() })}>Change Name</button>
<button onClick={() => updateAssignment({ list: assigment.list.concat(randomName()) })}>Add To List</button>
</div>
);
}
If you want to use traditional react class components you can use a higher order component like so:
This example demonstrates how to create a connected react component, this particular component listens for data in the default shard, under the key ['default', 'assignments', props.id]
. This means if the data at that key is updated, this component will receive an update including the new data.
It is important to note that the common pattern of incoming props checking for component updating when using mutastate will not function correctly, unless you make a deep copy of your incoming props for comparison yourself. The data passed into your component will be mutated!
Indicating { useProxy: true }
will allow you to modify the data directly (only simple data, objects, arrays, strings, numbers, no custom classes or functions) as we do in this example (see assignment.count += 1
). The data will not, in fact, be modified; the modification will be captured and converted into function calls to the current mutastate. (the previous assignment.count += 1
becomes mutastate.set('default.assignments[1].count', assignment.count + 1)
)
Also please note that the function is withMutastateCreator
instead of withMutastate
, this is to avoid the ambiguity of having a separate repository for react, this is subject to change in a major version far in the future, currently if you want a withMutastate
function you can create one by executing: const withMutastate = withMutastateCreator(React, { instance: yourMutastateInstance, useProxy: true });
;
import React from 'react';
import { useMutastate } from 'mutastate';
class Assignment extends React.Component {
constructor(props) {
super(props);
props.agent.listen(['default', 'assignments', props.id], { alias: 'assignment', defaultValue: { name: 'john', count: 0, list: [] } });
}
render() {
const { assignment } = this.props.data;
return (
<div>
<div>{assignment.name}</div>
<div>{assignment.count}</div>
<div>{JSON.stringify(assignment.list)}</div>
<button onClick={() => assignment.count += 1}>Add To Count</button>
<button onClick={() => assignment.name = ['a', 'b', 'c'][Math.floor(Math.random() * 3)]}>Change Name</button>
<button onClick={() => assignment.list.push('another')}>Add To List</button>
</div>
);
}
}
export default withMutastateCreator(React, { useProxy: true })(Assignment);
You can replicate mutastate to secondary instances, useful in circumstances where you don't have direct access to the same mutastate instance such as multi-window electron apps
// start replication, the send function will get called whenever any data in our instance changes (but will ignore changes that came from other instances). In this case we use a fake sendIpcMessage function
const receiver = singleton().replicate({ send: data => sendIpcMessage('state-sync', data) });
// this fictitious listenForIpcMessages function shows how you can receive data from an outside source to update your own mutastate
listenForIpcMessages('state-sync', (sender, data) => receiver(data));
The use of useProxy
will limit your browser availability due to use of the Proxy es6 feature:
If you must avoid useProxy
, the following mutastate methods are available:
get(key)
set(key, value)
delete(key)
assign(key, value)
push(key, value)
pop(key, value)
has(key)
getEverything(key)
setEverything(key)
FAQs
Mutable state management
The npm package mutastate receives a total of 5 weekly downloads. As such, mutastate popularity was classified as not popular.
We found that mutastate demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
Security News
Members Hub is conducting large-scale campaigns to artificially boost Discord server metrics, undermining community trust and platform integrity.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.