Last active
January 18, 2018 21:15
-
-
Save zerobias/7dd6a31293deb444fed661fc4819df03 to your computer and use it in GitHub Desktop.
Effector cheatsheet
This file contains hidden or 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 {Stream, fromPromise} from 'most' | |
import {message, effect, Effect, Message} from 'effector' | |
type State = { | |
currentUser: number, | |
} | |
/** | |
* Plain async function | |
*/ | |
async function fetchUserInfoCall( | |
userId: number | |
): Promise<User> { | |
return await invoke('UserInfo', { userId }) | |
} | |
/** Incoming trigger */ | |
const triggerUserInfo: Message<void> | |
= message('need to request current user info') | |
/** Effect which represented our async call */ | |
const requestUserInfo: Effect<number, User, UserNotFound> | |
= effect('async api user info request') | |
/** Epic where we could get something from state and run effect */ | |
triggerUserInfo.epic( | |
(trigger$: Stream<void>, state$: Stream<State>) => state$ | |
.sampleWith(trigger$) | |
.map(async ({ currentUser }) => { | |
const error = await requestUserInfo(currentUser).fail() | |
return warning({ | |
message: 'User not found!' | |
}) | |
}) | |
.map(fromPromise) | |
.join() | |
) | |
/** Subscription to messages about new requests */ | |
requestUserInfo.epic( params$ => params$.tap( | |
params => { | |
console.log('Request started') | |
} | |
)) | |
requestUserInfo.done.epic( result$ => result$.tap( | |
result => { | |
console.log('Request done') | |
} | |
)) | |
requestUserInfo.fail.epic( error$ => error$.tap( | |
error => { | |
console.log('Request failed') | |
} | |
)) | |
/** | |
* Now we need to provide implementation represented by requestUserInfo | |
*/ | |
requestUserInfo.serve(fetchUserInfoCall) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment