1.1.10 • Published 4 months ago
feather-state v1.1.10
Feather State
✨ A feather light state framework ✨ 468 bytes minified and gzipped - no dependencies
Companion frameworks:
Live examples:
Getting started
Package
npm i feather-state
...or inline
<head>
<script src="feather-state.min.js"></script>
</head>
<body>
<script>
const { store } = window.__feather__ || {};
</script>
</body>
Index
Usage
Documentation
Examples
Usage
Basic syntax
import { store } from 'feather-state';
const { watch, ...state } = store({
completeCount: 1,
todos: [{
title: 'Todo 1',
done: true
}, {
title: 'Todo 2',
done: false
}]
});
watch(state, 'todos', (next, prev) => {
console.log(next, prev);
});
function addTodo(title: string): void {
const newTodo = {
title: title,
done: false
};
state.todos = [
...todoStore.todos,
newTodo
];
};
Documentation
store()
const { watch, state } = store(null);
const { watch, state } = store(undefined);
const { watch, state } = store(true);
const { watch, state } = store(0);
const { watch, state } = store('Hello, World!');
const { watch, state } = store(['Item 1', 'Item 2']);
const { watch, ...state } = store({ key: 'value' });
Parameters
state
- value
Return values
state
|...state
- valuewatch()
- watch for shallow mutations
store().watch()
const unwatch = watch(parent, 'key', (next, prev) => {
console.log(next, prev);
});
Parameters
parent
- parent object of watched valuekey
- key of watched valuecallback()
- function called when value changes
Return value
unwatch()
- function to unwatch value
Examples
Object values
const { watch, ...state } = store({
isPlaying: true,
playPauseAriaLabel: 'Pause'
});
watch(state, 'isPlaying', (next) => {
if (next) {
videoEl.play();
state.playPauseAriaLabel = 'Pause';
} else {
videoEl.pause();
state.playPauseAriaLabel = 'Play';
}
});
const handleVisibilitychange = () => {
if (document.visibilityState === "visible") {
state.isPlaying = true;
} else {
state.isPlaying = false;
}
};
Primitive values
const { watch, ...isPlaying } = store(true);
const playPauseAriaLabel = store('Pause');
watch(isPlaying, 'state', (next) => {
if (next) {
videoEl.play();
playPauseAriaLabel.state = 'Pause';
} else {
videoEl.pause();
playPauseAriaLabel.state = 'Play';
}
});
const handleVisibilitychange = () => {
if (document.visibilityState === "visible") {
isPlaying.state = true;
} else {
isPlaying.state = false;
}
};
Roadmap 🚀
- Find more performant way of unwatching values
- Cleaner way of referencing values in watcher parameters
- Get even tinier in size