Skip to content

Instantly share code, notes, and snippets.

@cowboyd
Created February 14, 2019 19:38
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 cowboyd/4619e6b7c69144bcacce5ac50f7809bc to your computer and use it in GitHub Desktop.
Save cowboyd/4619e6b7c69144bcacce5ac50f7809bc to your computer and use it in GitHub Desktop.
Hypothetical effects API for microstates
import { act, every } from '@microstates/effects';
/**
* An effects function matches the state emitted by the store using
* the specified patterns. For every time the pattern is recognized,
* execute the callback with the matching object.
*
* This particular effects function recognizes every upload that is
* brand new and initiates the XHR, and also every upload that has
* been cancelled by the user and aborts it.
*/
export default act
.on({ uploads: every({ isNew: true })}, upload => {
let xhr = new XMLHttpRequest();
xhr.open('POST', URL);
xhr.onload = () => current = current.finish(xhr)
xhr.upload.onprogress = e => current = current.progress(e);
xhr.send(upload.file);
let current = upload.start(xhr);
})
.on({ uploads: every({ isCancelled: true })}, upload => {
let { xhr } = upload.state;
delete xhr.onload;
delete xhr.upload.onprogress;
xhr.abort();
upload.abort();
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment