forward
Formulae
forward({ from, to }): Subscription
When from
is triggered, send data from it to to
.
forward()
returns Subscription function, that can disconnect forward- if
from
is an array of Units,to
will be triggered if any fromfrom
is triggered - if
to
is an array of Units, whento
is triggered, each ofto
will 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,to
will 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 fromfrom
is triggered, each unit fromto
is 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.on
to update store. - Be careful when forwarding store to another store.
- Use Subscription with caution, because it breaks static connections and makes debug harder.