Skip to content

Instantly share code, notes, and snippets.

@kahlil
Last active November 19, 2015 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kahlil/bd92a2d6a07f26ce305d to your computer and use it in GitHub Desktop.
Save kahlil/bd92a2d6a07f26ce305d to your computer and use it in GitHub Desktop.
How to use @cycle/storage.
// Import Cycle core, the dom driver and the storage driver.
import Cycle from '@cycle/core';
import storageDriver from '@cycle/storage';
import { makeDOMDriver, h } from '@cycle/dom';
function main({DOM, storage}) {
// Create a stream of storage requests:
// 1. we select the desired input field
const storageRequest$ = DOM.select('input')
// 2. We listen to the keypress events.
.events('keypress')
// 3. We map the keypress event data that
// comes through the keypress stream to
// request objects that the storage driver
// expects.
.map(function(ev) {
return {
// We are not setting `target` and
// `action` because we want the defaults:
// `local` and `setItem`.
key: 'inputText',
value: ev.target.value
};
});
return {
// We pass the stream of write requests
// to the storage driver by assigning it
// here the the storage key.
storage: storageRequest$
// We feed the DOM driver with a virtual
// dom tree of just one input field. We
// want to set the value of the field
// to whatever is set in localStorage
// under the `inputText` key.
DOM: storage.local.getItem('inputText')
// If the localStorage Observable
// fails to produce a value
// we set the value as an empty string.
// If a value is produced startWith is ignored.
.startWith('')
// Whatever the stream produces gets
// mapped to a virtual dom tree and
// we set the value there.
.map((text) =>
h('input', {
type: 'text',
value: text
})
)
};
}
// Initialize the cycle.
Cycle.run(main, drivers);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment