Created
February 14, 2019 19:38
-
-
Save cowboyd/4619e6b7c69144bcacce5ac50f7809bc to your computer and use it in GitHub Desktop.
Hypothetical effects API for microstates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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