once
import { once } from 'patronum';
// or
import { once } from 'patronum/once';
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: Hello
messageReceived('World');
Alternative
import { createGate } from 'effector-react';
const PageGate = createGate();
sample({
source: once(PageGate.open),
target: fetchDataFx,
});