Skip to content

Merge guard and sample methods #521

Closed

Description

@val-o

Proposal

Provide an ability to transform data from clock and source in guard function.

Use case

Suppose we have a simple authentication flow, with following definitions

type UserName = string;
type Password = string;
type AuthFlowState = { type: 'WaitingUserName' } | WaitingPasswordState | { type: 'Done' };
type WaitingPasswordState = { type: 'WaitingPassword'; username: UserName };
declare const isWatingPassword: (state: AuthFlowState) => state is WaitingPasswordState;

const store$ = createStore<AuthFlowState>({ type: 'WaitingUserName' });

const submitPasswordEvent = createEvent<Password>();
type SubmitPasswordArgs = { password: Password; username: UserName };
const submitPassowrdFx = createEffect<SubmitPasswordArgs, unknown>();

guard({
  clock: submitPasswordEvent,
  source: store$,
  filter: isWatingPassword,
  target: submitPassowrdFx,
});
  • The submitPassowrdFx should be called once submitPasswordEvent is fired, but only when AuthFlowState is in the right state
  • Then we need to collect username from AuthFlowState and password from submitPasswordEvent params in order to call a submitPassowrdFx effect.

The code snipper above won't compile, due to types mismatch, because we also need to pass password from clock. If we would have a mapping function (like fn in sample), which would be called after filtering, we could easily shape a params expected by target effect

Workaround

We can achieve desired behaviour by combining sample with guard as follows:

sample({
  clock: guard({ clock: submitPasswordEvent, source: store$, filter: isWatingPassword }),
  source: submitPasswordEvent,
  fn: (sourceParams, clockParams): SubmitPasswordArgs => ({
    password: sourceParams,
    username: clockParams.username,
  }),
  target: submitPassowrdFx,
});

Activity

  1. doasync commented on Sep 6, 2021

    @doasync
    Member
  2. zerobias commented on Sep 6, 2021

    @zerobias
    Member

    The reason why fn is still missing in guard is purely technical - it is quite difficult to write types for guard, so we have not yet succeeded in implementing this feature

  3. zerobias commented on Nov 24, 2021

    @zerobias
    Member

    guard will be merged with the sample in the next minor release. right now I am working on types for this feature

  4. added this to the effector 22.2.0 milestone on Nov 24, 2021
  5. changed the title [-]Mapping function in guard method[/-] [+]Merge guard and sample methods[/+] on Jan 12, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    RFCRequest for Commentscoreeffector packageenhancementNew feature or request

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions