How to use the effector.sample function in effector

To help you get started, we’ve selected a few effector examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github zerobias / effector / examples / serverless-ssr / src / app.tsx View on Github external
<h3>Users:</h3>
    
    
  
)

export const installHistory = app.createEvent()
const changeLocation = app.createEvent()

// triggered when current location not equal new location
// and new location is valid user ID
const onValidLocation = guard(changeLocation, {
  filter: sample({
    source: combine({loc: location$, users: userList}),
    clock: changeLocation,
    fn: ({loc, users}, path) =&gt;
      loc !== path &amp;&amp; users.includes(path.replace('/user/', '')),
  }),
})

installHistory.watch(history =&gt; {
  const locationUpdate = scopeBind(changeLocation)
  history.listen(location =&gt; {
    locationUpdate(location.pathname)
  })
})

forward({
  from: startClient,
github zerobias / effector / examples / react-ssr / src / app.tsx View on Github external
<h3>Users:</h3>
    
    
  
)

export const installHistory = app.createEvent()
const changeLocation = app.createEvent()

// triggered when current location not equal new location
// and new location is valid user ID
const onValidLocation = guard(changeLocation, {
  filter: sample({
    source: location$,
    clock: changeLocation,
    fn: (loc, path) =&gt; loc !== path &amp;&amp; path.slice(1) in users,
  }),
})

installHistory.watch(history =&gt; {
  const locationUpdate = scopeBind(changeLocation)
  history.listen(location =&gt; {
    locationUpdate(location.pathname)
  })
})

forward({
  from: startClient,
  to: installHistory,
github howtocards / frontend / src / features / cards / model / registry.store.js View on Github external
import { type Card, cardsApi } from "@api/cards"
import {
  clearRegistry,
  setUsefulMark,
  usefulMarkClicked,
} from "./registry.events"

type Registry = { [id: number]: Card }

export const $registry: Store = createStore({})

export function getCard(cardId: number) {
  return $registry.getState()[cardId]
}

sample(
  $registry,
  usefulMarkClicked,
  (registry, cardId) =&gt; registry[cardId],
).watch((card) =&gt; {
  if (card)
    setUsefulMark({ cardId: card.id, isUseful: !card.permissions.isUseful })
})

$registry.reset(clearRegistry)

// Optimistic update
$registry.on(setUsefulMark, (registry, params) =&gt; {
  const card = registry[params.cardId]
  if (!card) return registry

  // eslint-disable-next-line no-param-reassign
github zerobias / effector / website / editor / src / share / controller.js View on Github external
return
    }
    const ref = urlRef.current
    if (!ref) return
    ref.select()
    document.execCommand('copy')
  },
})
const unexpectedSharingError = sharing.fail.filter({
  fn: ({error}) => error.name !== 'AbortError',
})
unexpectedSharingError.watch(({error}) => {
  console.error(error)
})
forward({
  from: sample(createStoreObject({slug, sharedUrl}), clickShare),
  to: sharing,
})

export const urlRef: any = React.createRef()
github zerobias / effector / website / editor / src / settings / init.js View on Github external
})

typeHoverToggle.on(typeHoverToggleChange, handler)

prettier.use(async code => {
  const result = await prettierRequest(code)
  if (typeof result.code !== 'string') {
    console.error('prettier request error', result)
    throw Error('request failed')
  }
  return result.code
})

sample({
  source: sourceCode,
  clock: sample(prettier.pending, clickPrettify).filter({
    fn: pending => !pending,
  }),
  target: prettier,
})

forward({
  from: prettier.done.map(({result}) => result),
  to: sourceCode,
})
github DTupalov / react-material-ui-datatable / src / model / createSelectedData.js View on Github external
$selectedData
    .on(handleSelect, (_, nextSelectedData) => nextSelectedData)
    .on(toggleSelectRow, (selectedData, selectedDataItem) => {
      const nextSelectedData = [...selectedData];
      const dataIndex = nextSelectedData.findIndex(
        data => data === selectedDataItem
      );
      if (dataIndex !== -1) {
        nextSelectedData.splice(dataIndex, 1);
      } else {
        nextSelectedData.push(selectedDataItem);
      }
      return nextSelectedData;
    })
    .on(sample($computedData, toggleSelectAll), (selectedData, computedData) =>
      selectedData.length ? [] : [...computedData]
    )
    .on(handleDelete, (selectedData, deletedData) =>
      selectedData.filter(dataIndex => !deletedData.includes(dataIndex))
    );

  return { $selectedData, toggleSelectRow, toggleSelectAll, handleSelect };
};
github zerobias / effector / website / editor / src / editor / init.js View on Github external
version.on(selectVersion, (_, p) => p)

codeCursorActivity.watch(editor => {
  const cursor = editor.getCursor()
  const body = editor.getValue()
  const line = cursor.line + 1
  const col = cursor.ch
  typeAtPos({
    filename: '/static/repl.js',
    body,
    line,
    col,
  })
})

sample({
  source: typeHoverToggle,
  clock: codeCursorActivity,
  fn: (enabled, editor) => ({enabled, editor}),
  //$off
}).watch(({enabled, editor}) => {
  const cursor = editor.getCursor()
  if (cursor.line === 0 && cursor.ch === 0) return
  if (enabled) {
    editor.addWidget(
      {
        line: cursor.line,
        ch: cursor.ch,
      },
      typeNode,
    )
    if (cursor.outside) {
github howtocards / frontend / src / pages / join / registration / model.js View on Github external
$isFormValid,
  registerFetching.isLoading,
  (isFormValid, isregisterFetching) => isFormValid && !isregisterFetching,
)

sample($isAuthenticated, formMounted).watch((isAuthenticated) => {
  if (isAuthenticated) history.replace("/")
})

const trimEvent = (event) => event.currentTarget.value.trim()

$email.on(emailChanged.map(trimEvent), (_, email) => email)
$password.on(passwordChanged.map(trimEvent), (_, password) => password)
$form.reset(formUnmounted).reset(formMounted)

sample(
  createStoreObject({ isSubmitEnabled: $isSubmitEnabled, form: $form }),
  formSubmitted,
).watch(({ form, isSubmitEnabled }) => {
  if (isSubmitEnabled) registerProcessing(form)
})

registerProcessing.use((form) =>
  accountApi.createAccount(form).then(() => sessionApi.createSession(form)),
)
registerProcessing.done.watch(({ result }) => {
  tokenChanged(result.token)
  history.push("/")
})
github tanyaisinmybed / effector-undo / src / index.ts View on Github external
.on(clear, ({ states, head }) =&gt; ({
      states: [states[head]],
      head: 0
    }));

  const current = history.map(({ states, head }) =&gt; states[head]);

  const shouldSave = createStore({
    next: initialState,
    prev: initialState
  })
    .on(store, ({ next: prev }, next) =&gt; ({ next, prev }))
    .map(({ next, prev }) =&gt; filter(next, prev));

  guard({
    source: sample(store, merge(events)),
    filter: shouldSave,
    target: push
  });

  forward({
    from: current,
    to: store
  });

  return { undo, redo, clear, history };
}
github howtocards / frontend / src / pages / join / registration / model.js View on Github external
})

const $isFormValid = combine(
  $isPasswordCorrect,
  $isEmailCorrect,
  (isPasswordCorrect, isEmailCorrect) =&gt; isPasswordCorrect &amp;&amp; isEmailCorrect,
)

export const $isFormDisabled = registerFetching.isLoading
export const $isSubmitEnabled: Store = combine(
  $isFormValid,
  registerFetching.isLoading,
  (isFormValid, isregisterFetching) =&gt; isFormValid &amp;&amp; !isregisterFetching,
)

sample($isAuthenticated, formMounted).watch((isAuthenticated) =&gt; {
  if (isAuthenticated) history.replace("/")
})

const trimEvent = (event) =&gt; event.currentTarget.value.trim()

$email.on(emailChanged.map(trimEvent), (_, email) =&gt; email)
$password.on(passwordChanged.map(trimEvent), (_, password) =&gt; password)
$form.reset(formUnmounted).reset(formMounted)

sample(
  createStoreObject({ isSubmitEnabled: $isSubmitEnabled, form: $form }),
  formSubmitted,
).watch(({ form, isSubmitEnabled }) =&gt; {
  if (isSubmitEnabled) registerProcessing(form)
})