once
import { once } from 'patronum';// orimport { once } from 'patronum/once';
target = once(source)
Motivation
The method allows to do something only on the first ever trigger of source
.
It is useful to trigger effects or other logic only once per application’s lifetime.
Formulae
target = once(source);
- When
source
is triggered, launchtarget
with data fromsource
, but only once.
Arguments
source
(Event<T>
|Effect<T>
|Store<T>)
— Source unit, data from this unit is used bytarget
.
Returns
target
Event<T>
— The event that will be triggered exactly once aftersource
is triggered.
Example
const messageReceived = createEvent<string>();const firstMessageReceived = once(messageReceived);
firstMessageReceived.watch((message) => console.log('First message received:', message),);
messageReceived('Hello'); // First message received: HellomessageReceived('World');
Alternative
import { createGate } from 'effector-react';
const PageGate = createGate();
sample({ source: once(PageGate.open), target: fetchDataFx,});
target = once({ source, reset })
Motivation
This overload may receive reset
in addition to source
. If reset
is fired,
target
will be allowed to trigger one more time, when source
is called.
Formulae
target = once({ source, reset });
- When
source
is triggered, launchtarget
with data fromsource
, but only once. - When
reset
is triggered, letonce
be reset to the initial state and allowtarget
to be triggered again uponsource
being called.
Arguments
source
(Event<T>
|Effect<T>
|Store<T>)
— Source unit, data from this unit is used bytarget
.reset
(Event
|Effect
|Store)
— A unit that resetsonce
to the initial state, allowingtarget
to be triggered again.
Returns
target
Event<T>
— The event that will be triggered once aftersource
is triggered, untilonce
is reset by callingreset
.
Example
import { createGate } from 'effector-react';
const PageGate = createGate();
sample({ source: once({ source: PageGate.open, reset: fetchDataFx.fail, }), target: fetchDataFx,});