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.

Revisions

  1. Kelin2025 revised this gist Apr 29, 2019. 1 changed file with 4 additions and 1 deletion.
    5 changes: 4 additions & 1 deletion effect.js
    Original file line number Diff line number Diff line change
    @@ -37,4 +37,7 @@ getPost.done.watch(({ params, result }) => {
    getPost.fail.watch(({ params, error }) => {
    console.log(params) // { id }
    console.log(error) // Error
    })
    })

    // Just call getPost with payload
    getPost({ id: 1 })
  2. Kelin2025 created this gist Apr 29, 2019.
    40 changes: 40 additions & 0 deletions effect.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    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
    })