createEffect(name?, { handler })

Creates an effect

Arguments

  1. name? (string): Effect name
  2. params? (Params): Setup effect
    • handler (Function): function to handle effect calls, also can be set with use(handler)

Returns

(Effect): A container for async function.

Note: You are not supposed to Forward parts of Effect (even though it consists of Events and Stores), since it's a complete entity on its own. This behavior will not be supported

Examples

Create unnamed effect

import {createEffect} from 'effector'
const fetchUserRepos = createEffect({
handler: async ({name}) => {
const url = `https://api.github.com/users/${name}/repos`
const req = await fetch(url)
return req.json()
},
})

Try it

Create named effect

import {createEffect} from 'effector'
const fetchUserRepos = createEffect('fetch user repositories', {
handler: async ({name}) => {
const url = `https://api.github.com/users/${name}/repos`
const req = await fetch(url)
return req.json()
},
})

Try it

Set handler to effect after creating

import {createEffect} from 'effector'
const fetchUserRepos = createEffect()
fetchUserRepos.use(async ({name}) => {
const url = `https://api.github.com/users/${name}/repos`
const req = await fetch(url)
return req.json()
})

Try it

Watch effect status

import {createEffect} from 'effector'
const fetchUserRepos = createEffect({
handler: async ({name}) => {
const url = `https://api.github.com/users/${name}/repos`
const req = await fetch(url)
return req.json()
},
})
fetchUserRepos.pending.watch(pending => {
console.log(`effect is pending?: ${pending ? 'yes' : 'no'}`)
})
fetchUserRepos.done.watch(({params, result}) => {
console.log(params) // {name: 'zerobias'}
console.log(result) // resolved value
})
fetchUserRepos.fail.watch(({params, error}) => {
console.error(params) // {name: 'zerobias'}
console.error(error) // rejected value
})
fetchUserRepos.finally.watch(({params, status, result, error}) => {
console.log(params) // {name: 'zerobias'}
console.log(`handler status: ${status}`)
if (error) {
console.log('handler rejected', error)
} else {
console.log('handler resolved', result)
}
})
fetchUserRepos({name: 'zerobias'})

Try it

Change state

import {createStore, createEffect} from 'effector'
const fetchUserRepos = createEffect({
handler: async ({name}) => {
const url = `https://api.github.com/users/${name}/repos`
const req = await fetch(url)
return req.json()
},
})
const repos = createStore([]).on(
fetchUserRepos.done,
(_, {result: repos}) => repos,
)

Try it