Last active
May 29, 2022 07:01
-
-
Save Kelin2025/7a5960cea84dee78afc3e60cfa592b27 to your computer and use it in GitHub Desktop.
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 { createStore, createEffect } from 'effector' | |
const getPost = createEffect('Fetch posts') | |
const $isLoading = createStore(false) | |
const $post = createStore(null) | |
const $error = createStore(null) | |
$isLoading | |
.on(getPost, () => true) | |
.on(getPost.done, () => false) | |
.on(getPost.fail, () => false) | |
$post | |
.on(getPost, () => null) | |
.on(getPost.done, (state, { result }) => result) | |
$error | |
.on(getPost, () => null) | |
.on(getPost.fail, (state, { error }) => error) | |
// Fetch post on effect call | |
getPost.use(({ id }) => fetch(`/posts/${id}`).then(r => r.json())) | |
// When effect is called | |
getPost.watch(params => { | |
console.log(params) // { id } | |
}) | |
// When effect is resolved | |
getPost.done.watch(({ params, result }) => { | |
console.log(params) // { id } | |
console.log(result) // Response JSON | |
}) | |
// When effect is rejected | |
getPost.fail.watch(({ params, error }) => { | |
console.log(params) // { id } | |
console.log(error) // Error | |
}) | |
// Just call getPost with payload | |
getPost({ id: 1 }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment