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: New effect

Note: You must provide a handler either through handler property in createEffect or .use method later, otherwise the error "no handler used in %effect name%" will appear in the console

Note: You are not supposed to Forward to 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 fetchUserReposFx = createEffect({
handler: async ({name}) => {
const url = `https://api.github.com/users/${name}/repos`
const req = await fetch(url)
return req.json()
},
})
await fetchUserReposFx({name: 'zerobias'})

Try it

Create named effect

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

Try it

Set handler to effect after creating

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

Try it

Watch effect status

import {createEffect} from 'effector'
const fetchUserReposFx = createEffect({
handler: async ({name}) => {
const url = `https://api.github.com/users/${name}/repos`
const req = await fetch(url)
return req.json()
},
})
fetchUserReposFx.pending.watch(pending => {
console.log(`effect is pending?: ${pending ? 'yes' : 'no'}`)
})
fetchUserReposFx.done.watch(({params, result}) => {
console.log(params) // {name: 'zerobias'}
console.log(result) // resolved value
})
fetchUserReposFx.fail.watch(({params, error}) => {
console.error(params) // {name: 'zerobias'}
console.error(error) // rejected value
})
fetchUserReposFx.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)
}
})
await fetchUserReposFx({name: 'zerobias'})

Try it

Change state

import {createStore, createEffect} from 'effector'
const fetchUserReposFx = 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(fetchUserReposFx.doneData, (_, repos) => repos)
await fetchUserReposFx({name: 'zerobias'})

Try it

Last updated on