Skip to content

Instantly share code, notes, and snippets.

@Kelin2025
Last active May 29, 2022 07:01
Show Gist options
  • Save Kelin2025/7a5960cea84dee78afc3e60cfa592b27 to your computer and use it in GitHub Desktop.
Save Kelin2025/7a5960cea84dee78afc3e60cfa592b27 to your computer and use it in GitHub Desktop.
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