fork
since
effector 21.0.0
fork(domain: Domain, { values?, handlers? }?): Scope
Creates a fully isolated instance of application. The primary purpose of fork includes SSR (but is not limited to). Fork clones all the units and connections between them leading to completely independents copy of all logic defined within domain.
Arguments
domain
(Domain): Original domain to clone, requiredvalues
Optional object with either a mapping from store sids (babel-plugin is required to allowsid
generation) to store values or a Map where keys are Store objects and values contains initial store valuehandlers
Optional object with either a mapping from effect sids (babel-plugin is required to allowsid
generation) to effect handlers or a Map where keys are Effect objects and values contains handlers
Returns
Scope object containing information about cloned domain
Example
Create two instances with independent counter state
import {
createStore,
createEvent,
createDomain,
forward,
fork,
allSettled,
} from 'effector'
const domain = createDomain()
const inc = domain.createEvent()
const dec = domain.createEvent()
const $counter = domain
.createStore(0)
.on(inc, value => value + 1)
.on(dec, value => value - 1)
const scopeA = fork(domain)
const scopeB = fork(domain)
await allSettled(inc, {scope: scopeA})
await allSettled(dec, {scope: scopeB})
console.log($counter.getState()) // => 0
console.log(scopeA.getState($counter)) // => 1
console.log(scopeB.getState($counter)) // => -1
Support Map in values
since
effector 20.11.0
fork(domain: Domain, { values?: Map<Store, any> , handlers? }?): Scope
Support change effects
since
effector 20.16.0
Support for handlers to fork to change effect handlers for forked scope (useful for testing)
//app
const app = createDomain()
const fetchFriends = app.createEffect<{limit: number}, string[]>({
async handler({limit}) {
/* some client-side data fetching */
return []
},
})
const user = app.createStore('guest')
const friends = app
.createStore([])
.on(fetchFriends.doneData, (_, result) => result)
/*
test to ensure that friends value is populated
after fetchFriends call
*/
const testScope = fork(app, {
values: {
[user.sid]: 'alice',
},
handlers: {
[fetchFriends.sid]: () => ['bob', 'carol'],
},
})
/* trigger computations in scope and await all called effects */
await allSettled(fetchFriends, {
scope: testScope,
params: {limit: 10},
})
/* check value of store in scope */
console.log(testScope.getState(friends))
// => ['bob', 'carol']