An effect that will start, stop, or conditionally run based on conditions set in the passed options. Some use cases for this effect include:
- Running initialization logic only one time.
- Validating values only after all required signals are set.
- Stopping effects that are no longer needed.
In addition to standard effect options, the following options are available:
- if: A function that must be true for the effect to run.
- start: A function that must return true for the effect to start running. Once it is true once, it will not be checked again.
- times: The number of times the effect should run.
- until: A function that stop that effect as soon as it returns true.
Example: Initialization Side Effect
This will only execute once after $userInfo has a value, and then the effect will be properly destroyed.
const $userInfo = signal<UserInfo | undefined>(undefined);
gatedEffect(() => doSomethingWithRequiredUserInfo($userInfo()!),
{ start: () => $userInfo() !== undefined, times: 1 });
Example: Logging an Invalid State
This will log errors only after values have been set.
const $userName = signal<string | undefined>(undefined);
const $address = signal<string | undefined>(undefined);
gatedEffect(() => logMissingRequiredData()),
{ start: () => !!$userInfo() || !!$address() , if: () => !$userInfo() || !$address() });