forward
Formulae
forward({ from, to }): Subscription
When fromis triggered, send data from it to to.
forward()returns Subscription function, that can disconnect forward- if
fromis an array of Units,towill be triggered if any fromfromis triggered - if
tois an array of Units, whentois triggered, each oftowill be triggered too - Unit is an interface, that implemented by Event, Store, Effect
forward({ from: Unit, to: Unit })
Sends data from one entity to another.
Arguments
from(Event | Store | Effect): Source of data. Forward will listen for changes of this unit.to(Event | Store | Effect): Target for data. Forward will trigger this unit with data fromfrom.
Data type of the from and to should be equal
Returns
Subscription: Unsubscribe function. It breaks connection between from and to. After call, to will not be triggered anymore.
Example
Send store data to store
import { createStore, createEvent, forward } from 'effector'
const $store = createStore(1)
const event = createEvent()
forward({
from: event,
to: $store,
})
$store.watch((state) => console.log('store changed: ', state))
// => store changed: 1
event(200)
// => store changed: 200
It is the not better way to update store. In most cases you need store.on
forward({ from: Array<Unit>, to: Array<Unit> })
from(Array<Event | Store | Effect>): List of units. When triggered one from list,towill be triggered with data from it.- Array can contain different type of units, but data type must fit together.
to(Array<Event | Store | Effect>): List of targets. When unit fromfromis triggered, each unit fromtois called with data from unitfrom.
- Array can contain different type of units, but data type must fit together.
Data type of the from and to must be equal
Subscription: Unsubscribe function. It breaks connection between from and to. After call, to will not be triggered anymore.
Example
import { createEvent, forward } from 'effector'
const firstSource = createEvent()
const secondSource = createEvent()
const firstTarget = createEvent()
const secondTarget = createEvent()
forward({
from: [firstSource, secondSource],
to: [firstTarget, secondTarget],
})
firstTarget.watch((e) => console.log('first target', e))
secondTarget.watch((e) => console.log('second target', e))
firstSource('A')
// => first target A
// => second target A
secondSource('B')
// => first target B
// => second target B
Combination
Also, you can combine array with simple unit:
forward({
from: singleSource,
to: [$store, event, effect],
})
// Another example
forward({
from: [firstSource, secondSource, $store],
to: [event, effect, anotherEffect],
})
Recommendation
- Use
store.onto update store. - Be careful when forwarding store to another store.
- Use Subscription with caution, because it breaks static connections and makes debug harder.