### Effector App Logic with Interval for Testing Source: https://github.com/effector/withease/blob/master/apps/website/docs/magazine/explicit_start.md Illustrates a typical Effector module with a store, an event, and an effect that starts an interval to increment the store. This example highlights the challenges of testing implicitly started logic. ```typescript // app.ts import { createStore, createEvent, sample, scopeBind } from 'effector'; const $counter = createStore(0); const increment = createEvent(); const startIncrementationIntervalFx = createEffect(() => { const boundIncrement = scopeBind(increment, { safe: true }); setInterval(() => { boundIncrement(); }, 1000); }); sample({ clock: increment, source: $counter, fn: (counter) => counter + 1, target: $counter, }); startIncrementationIntervalFx(); ``` -------------------------------- ### Effector Server-Side Rendering Setup Source: https://github.com/effector/withease/blob/master/apps/website/docs/magazine/explicit_start.md Shows a minimal server setup for an Effector application, indicating where application logic would be integrated. This highlights the necessity of explicit startup for SSR. ```typescript // server.ts import * as app from './app'; function handleRequest(req, res) { // ... } ``` -------------------------------- ### Install @withease/contracts with Package Managers Source: https://github.com/effector/withease/blob/master/apps/website/docs/contracts/index.md Demonstrates how to install the @withease/contracts package using popular package managers: pnpm, yarn, and npm. This is the first step before using the library. ```sh pnpm install @withease/contracts ``` ```sh yarn add @withease/contracts ``` ```sh npm install @withease/contracts ``` -------------------------------- ### Async Redux Integration Setup Source: https://github.com/effector/withease/blob/master/apps/website/docs/redux/index.md Allows deferring the initialization of the Redux-Effector interop object and Redux store creation. The store can be provided later via a setup event, which is useful for managing cyclic dependencies. ```ts // src/shared/redux-interop export const startReduxInterop = createEvent(); export const reduxInterop = createReduxIntegration({ setup: startReduxInterop, }); // src/entrypoint.ts import { startReduxInterop } from 'shared/redux-interop'; const myReduxStore = configureStore({ // ... }); startReduxInterop(myReduxStore); // or, if you use the Fork API allSettled(startReduxInterop, { scope: clientScope, params: myReduxStore, }); ``` -------------------------------- ### Install @withease/redux Source: https://github.com/effector/withease/blob/master/apps/website/docs/redux/index.md Installs the @withease/redux package using different package managers (pnpm, yarn, npm). ```sh pnpm install @withease/redux ``` ```sh yarn add @withease/redux ``` ```sh npm install @withease/redux ``` -------------------------------- ### Track Page Visibility with Effector Source: https://github.com/effector/withease/blob/master/apps/website/docs/web-api/page_visibility.md Initializes page visibility tracking using `trackPageVisibility`. It requires a `setup` event to install listeners and returns Effector Events (`visible`, `hidden`) and Stores (`$visible`, `$hidden`) to manage visibility state. The integration uses the Page Visibility API. ```typescript import { trackPageVisibility } from '@withease/web-api'; const { visible, hidden, $visible, $hidden } = trackPageVisibility({ setup: appStarted, }); ``` -------------------------------- ### Track Preferred Languages with Effector Source: https://github.com/effector/withease/blob/master/apps/website/docs/web-api/preferred_languages.md Initializes the preferred language tracking integration. It requires a `setup` event to install listeners and optionally accepts a `teardown` event for cleanup. It returns stores for the current language and preferred languages, and an event for language changes. ```typescript import { trackPreferredLanguages } from '@withease/web-api'; const { $language, $languages, languageChanged } = trackPreferredLanguages({ setup: appStarted, }); ``` -------------------------------- ### Install @withease/web-api with pnpm, yarn, or npm Source: https://github.com/effector/withease/blob/master/apps/website/docs/web-api/index.md Installs the @withease/web-api package using different package managers. Choose the command corresponding to your project's package manager. ```sh pnpm install @withease/web-api ``` ```sh yarn add @withease/web-api ``` ```sh npm install @withease/web-api ``` -------------------------------- ### Track Device Screen Orientation with Effector Source: https://github.com/effector/withease/blob/master/apps/website/docs/web-api/screen_orientation.md Initializes screen orientation tracking using Effector. It requires a `setup` event for installation and returns stores for orientation type, angle, and boolean flags for portrait/landscape modes. It leverages the Screen Orientation API. ```typescript import { trackScreenOrientation } from '@withease/web-api'; const { $type, $angle, $portrait, $landscape } = trackScreenOrientation({ setup: appStarted, }); ``` -------------------------------- ### Install patronum/debug for Effector Source: https://github.com/effector/withease/blob/master/apps/website/docs/magazine/watch_calls.md Installs the patronum library, which provides enhanced debugging capabilities for Effector. This is a prerequisite for using the debug method. ```sh pnpm install patronum ``` ```sh yarn add patronum ``` ```sh npm install patronum ``` -------------------------------- ### Install @withease/factories Package Source: https://github.com/effector/withease/blob/master/apps/website/docs/factories/index.md Instructions for installing the @withease/factories package using different package managers (pnpm, yarn, npm). ```sh pnpm install @withease/factories ``` ```sh yarn add @withease/factories ``` ```sh npm install @withease/factories ``` -------------------------------- ### Import Effector Ecosystem Data (TypeScript) Source: https://github.com/effector/withease/blob/master/apps/website/docs/statements/ecosystem.md Imports the 'ecosystem' data from a local file, likely containing information about Effector-compatible libraries. This is a common setup pattern for managing external library data within a project. ```typescript import { ecosystem } from '../ecosystem.ts' ``` -------------------------------- ### Initialize with Replaceable Static i18next Instance Source: https://github.com/effector/withease/blob/master/apps/website/docs/i18next/index.md Creates an i18next integration using a replaceable static i18next instance. This method is suitable for scenarios where the i18next instance might need to be swapped out later, for example, during client-side or server-side rendering forks. It requires an Effector event to signal the setup completion. ```ts import i18next from 'i18next'; import { createStore, createEvent, fork, allSettled } from 'effector'; import { createI18nextIntegration } from '@withease/i18next'; // Event that should be called after application initialization const appStarted = createEvent(); // Create Store for i18next instance const $i18nextInstance = createStore(i18next.createInstance(/* ... */), { serialize: 'ignore', }); const integration = createI18nextIntegration({ // Pass Store with i18next instance to the integration instance: $i18nextInstance, setup: appStarted, }); // You can replace $someInstance later during runtime // e.g., during fork on client or server ``` -------------------------------- ### Create Redux Integration Source: https://github.com/effector/withease/blob/master/apps/website/docs/redux/index.md Initializes Redux-Effector interoperability by creating an interop object. It requires a Redux store instance and an optional setup event for initialization. This allows Effector to interact with the Redux store. ```ts const myReduxStore = configureStore({ // ... }); const reduxInterop = createReduxIntegration({ reduxStore: myReduxStore, setup: appStarted, }); ``` -------------------------------- ### Install Effector i18next Integration Source: https://github.com/effector/withease/blob/master/apps/website/docs/i18next/index.md Installs the @withease/i18next package and its peer dependency i18next using different package managers (pnpm, yarn, npm). ```sh pnpm install @withease/i18next i18next ``` ```sh yarn add @withease/i18next i18next ``` ```sh npm install @withease/i18next i18next ``` -------------------------------- ### Create a custom interval trigger with Effector @@trigger Source: https://github.com/effector/withease/blob/master/apps/website/docs/protocols/trigger.md This example demonstrates how to create a custom trigger that fires every second. It utilizes Effector's core utilities like `createEvent`, `createStore`, `createEffect`, `scopeBind`, and `sample` to manage the interval and its lifecycle. The trigger adheres to the `@@trigger` protocol, providing `setup` and `fired` events. ```typescript import { createEvent, createStore, createEffect, scopeBind, sample, } from 'effector'; const intervalTrigger = { '@@trigger': () => { const setup = createEvent(); const fired = createEvent(); const teardown = createEvent(); const $interval = createStore(null); const startInternalFx = createEffect(() => { const boundFired = scopeBind(fired, { safe: true }); return setInterval(boundFired, 1000); }); const stopIntervalFx = createEffect(clearInterval); sample({ clock: setup, target: startInternalFx }); sample({ clock: startInternalFx.doneData, target: $interval }); sample({ clock: teardown, source: $interval, target: stopIntervalFx }); sample({ clock: stopIntervalFx.done, target: $interval.reinit }); return { setup, fired }; }, }; ``` -------------------------------- ### Async Redux Interoperability Setup (Effector/TypeScript) Source: https://github.com/effector/withease/blob/master/apps/website/docs/magazine/migration_from_redux.md Demonstrates an alternative asynchronous setup for Redux interoperability to avoid cyclic dependencies. The `createReduxIntegration` is configured with an event that will later receive the Redux store, requiring null checks if accessed before initialization. ```typescript // src/shared/redux-interop import { createEvent } from 'effector'; import { createReduxIntegration, ReduxStore } from '@withease/redux'; export const startReduxInterop = createEvent(); export const reduxInterop = createReduxIntegration({ setup: startReduxInterop, }); // src/entrypoint.ts import { startReduxInterop } from 'shared/redux-interop'; import { configureStore } from '@reduxjs/toolkit'; const myReduxStore = configureStore({ // ... }); startReduxInterop(myReduxStore); ``` -------------------------------- ### Create and Trigger App Start Event with Scope in Effector Source: https://github.com/effector/withease/blob/master/apps/website/docs/magazine/explicit_start.md Demonstrates creating an Effector `Event` for app startup and triggering it within a specific `Scope`. This pattern provides control over the app's lifecycle and prevents unexpected behavior by isolating state. ```typescript import { createEvent, fork, allSettled } from "effector"; const appStarted = createEvent(); const scope = fork(); await allSettled(appStarted, { scope }); ``` -------------------------------- ### Effector Test Case Structure Source: https://github.com/effector/withease/blob/master/apps/website/docs/magazine/explicit_start.md Provides a basic structure for testing Effector applications, focusing on verifying store updates over time. This demonstrates how explicit app startup is crucial for isolating test scenarios. ```typescript // app.test.ts import { $counter } from './app'; test('$counter should be 5 after 5 seconds', async () => { // ... test }); test('$counter should be 10 after 10 seconds', async () => { // ... test }); ``` -------------------------------- ### Effector Media Query Tracking with @@trigger Protocol Source: https://github.com/effector/withease/blob/master/apps/website/docs/web-api/media_query.md Demonstrates using `trackMediaQuery` with the `@@trigger` protocol, which allows direct firing of the `matched` event without explicit `setup` and `teardown` events. This simplifies integration when the function is expected to trigger an action. ```typescript import { trackMediaQuery } from '@withease/web-api'; somethingExpectsTrigger(trackMediaQuery('(max-width: 600px)')); ``` -------------------------------- ### Example Usage in Vue with Effector-Vue Source: https://github.com/effector/withease/blob/master/apps/website/docs/factories/index.md Demonstrates how to integrate the invoked factory units ($counter, increment, decrement) into a Vue 3 component using the `useUnit` composition API from `effector-vue`. ```html ``` -------------------------------- ### Trigger Protocol Example for Preferred Languages Source: https://github.com/effector/withease/blob/master/apps/website/docs/web-api/preferred_languages.md Demonstrates how `trackPreferredLanguages` supports the `@@trigger` protocol. When the `@@trigger` protocol is used, the `trackPreferredLanguages` function triggers the `languageChanged` event as a `fired` event. ```typescript import { trackPreferredLanguages } from '@withease/web-api'; somethingExpectsTrigger(trackPreferredLanguages); ``` -------------------------------- ### Bulk Store Reset with Domains (Effector) Source: https://github.com/effector/withease/blob/master/apps/website/docs/magazine/no_domains.md Shows how Effector Domains can be used to perform bulk operations, specifically resetting multiple stores with a single event. This example highlights the implicit nature of domain-based bulk operations. ```typescript import { createDomain, createStore, createEvent } from 'effector'; const domain = createDomain(); export const someEvent = createEvent({ domain }); export const $store1 = createStore(0, { domain }); export const $store2 = createStore(0, { domain }); export const $store3 = createStore(0, { domain }); // 👇 callback will be called on every Store in the Domain domain.onCreateStore((store) => { store.reset(someEvent); }); ``` -------------------------------- ### Initialize with Replaceable Asynchronous i18next Instance Source: https://github.com/effector/withease/blob/master/apps/website/docs/i18next/index.md Initializes the i18next integration with a replaceable asynchronous i18next instance. This is useful when the i18next instance needs to be created asynchronously, for instance, by an Effector Effect. The integration setup is triggered by a provided Effector event. ```ts import i18next from 'i18next'; import { createStore, createEvent, fork, allSettled } from 'effector'; import { createI18nextIntegration } from '@withease/i18next'; // Event that should be called after application initialization const appStarted = createEvent(); // Create Effect that creates i18next instance const createI18nextFx = createEffect(() => i18next.use(/* ... */).init(/* ... */) ); const integration = createI18nextIntegration({ // Pass Effect that creates i18next instance to the integration instance: createI18nextFx, setup: appStarted, }); // You can replace createI18nextFx later during runtime // e.g., during fork on client or server ``` -------------------------------- ### Primitive Type Validation with @withease/contracts Source: https://context7.com/effector/withease/llms.txt Demonstrates the usage of built-in primitive contracts (`bool`, `num`, `str`) from `@withease/contracts` for validating boolean, number, and string types respectively. Includes examples of successful and failed validations, and error message retrieval. ```typescript import { bool, num, str } from '@withease/contracts'; // Boolean validation console.log(bool.isData(true)); // true console.log(bool.isData(42)); // false // Number validation console.log(num.isData(42)); // true console.log(num.isData('42')); // false // String validation console.log(str.isData('hello')); // true console.log(str.isData(42)); // false console.log(str.getErrorMessages(42)); // ['expected string, got number'] ``` -------------------------------- ### Track Multiple Media Queries with Effector Source: https://github.com/effector/withease/blob/master/apps/website/docs/web-api/media_query.md Tracks the matching state of multiple media queries simultaneously. It returns an object where each key corresponds to a query name, providing its own `$matches` store and `matched` event. Requires `setup` event for initialization. ```typescript import { trackMediaQuery } from '@withease/web-api'; const { mobile, desktop } = trackMediaQuery( { mobile: '(max-width: 600px)', desktop: '(min-width: 601px)' }, { setup: appStarted } ); mobile.$matches; // Store mobile.matched; // Event desktop.$matches; // Store desktop.matched; // Event ``` -------------------------------- ### Render Ecosystem Libraries List (Vue.js) Source: https://github.com/effector/withease/blob/master/apps/website/docs/statements/ecosystem.md Renders an unordered list of ecosystem libraries using Vue.js. It iterates over the 'ecosystem' array, displaying each library's title and details, linked by its URL. This is a standard client-side rendering approach for dynamic lists. ```html ``` -------------------------------- ### Trigger App Start Event (Effector/React) Source: https://github.com/effector/withease/blob/master/apps/website/docs/magazine/migration_from_redux.md Illustrates how to trigger the `appStarted` event in an Effector application, typically near the root rendering point. This action signals the application's readiness and can initiate various setup processes, including Redux-Effector interoperability. ```typescript // src/entrypoint.ts import { appStarted } from 'root/shared/app-lifecycle'; import { render } from 'react-dom'; appStarted(); render(); ``` -------------------------------- ### Track Single Media Query with Effector Source: https://github.com/effector/withease/blob/master/apps/website/docs/web-api/media_query.md Tracks the matching state of a single media query using Effector. It returns a store `$matches` indicating if the query matches and an event `matched` fired when the query starts matching. Requires `setup` event for initialization. ```typescript import { trackMediaQuery } from '@withease/web-api'; const { $matches, matched } = trackMediaQuery('(max-width: 600px)', { setup: appStarted, }); ``` -------------------------------- ### Create Factories with `createFactory` and `invoke` from @withease/factories Source: https://context7.com/effector/withease/llms.txt Demonstrates how to use `createFactory` to define factory functions and `invoke` to call them, ensuring controlled execution and enabling dependency injection. This pattern is useful with state management libraries like Effector. ```typescript import { createFactory, invoke } from '@withease/factories'; import { createStore, createEvent, sample } from 'effector'; // Define a factory for creating a counter model const createCounter = createFactory((config: { initial?: number } = {}) => { const $count = createStore(config.initial ?? 0); const increment = createEvent(); const decrement = createEvent(); const reset = createEvent(); $count .on(increment, (n) => n + 1) .on(decrement, (n) => n - 1) .reset(reset); return { $count, increment, decrement, reset }; }); // Use the factory via invoke const counter = invoke(createCounter, { initial: 10 }); console.log(counter.$count.getState()); // 10 counter.increment(); console.log(counter.$count.getState()); // 11 // Factory without parameters const simpleCounter = invoke(createCounter); console.log(simpleCounter.$count.getState()); // 0 ``` -------------------------------- ### trackScreenOrientation Source: https://context7.com/effector/withease/llms.txt Creates reactive stores for tracking the device's screen orientation, including type (portrait/landscape) and rotation angle. Allows for UI adaptation based on orientation changes. ```APIDOC ## trackScreenOrientation(config) ### Description Creates reactive stores for tracking device screen orientation. ### Method N/A (Function call that returns stores) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { trackScreenOrientation } from '@withease/web-api'; import { createEvent, sample } from 'effector'; const setup = createEvent(); const teardown = createEvent(); const orientation = trackScreenOrientation({ setup, teardown }); setup(); // Orientation type: 'portrait-primary' | 'portrait-secondary' | 'landscape-primary' | 'landscape-secondary' console.log(orientation.$type.getState()); // Rotation angle in degrees console.log(orientation.$angle.getState()); // 0, 90, 180, or 270 // Boolean states for layout decisions console.log(orientation.$portrait.getState()); // true if portrait console.log(orientation.$landscape.getState()); // true if landscape ``` ### Response #### Success Response (200) N/A (Returns Effector stores) #### Response Example ```json { "$type": "portrait-primary", "$angle": 0, "$portrait": true, "$landscape": false } ``` ``` -------------------------------- ### Create Reactive Translated Stores - Effector i18next Source: https://context7.com/effector/withease/llms.txt Explains how to create reactive stores for translations using the `translated` function from `@withease/i18next`. It supports simple key lookups, dynamic keys with reactive variables, and template literal syntax for key construction. ```typescript import { createI18nextIntegration } from '@withease/i18next'; import { createStore, createEvent } from 'effector'; import i18next from 'i18next'; const setup = createEvent(); const { translated, $t } = createI18nextIntegration({ instance: i18next, setup, }); setup(); // Method 1: Simple key const $title = translated('page.title'); // Method 2: Key with reactive variables const $userName = createStore('Alice'); const $greeting = translated('greeting', { name: $userName }); // When $userName changes, $greeting automatically updates $userName.setState('Bob'); // $greeting now shows translation with name='Bob' // Method 3: Template literal syntax for dynamic keys const $section = createStore('home'); const $dynamicTitle = translated`page.${$section}.title`; // When $section changes, the translation key changes $section.setState('about'); // $dynamicTitle now translates 'page.about.title' ``` -------------------------------- ### trackPageVisibility Source: https://context7.com/effector/withease/llms.txt Creates reactive stores for tracking the visibility state of the web page (visible/hidden). Useful for pausing or resuming operations like polling or animations when the tab is not active. ```APIDOC ## trackPageVisibility(config) ### Description Creates reactive stores for tracking page visibility state (visible/hidden). ### Method N/A (Function call that returns stores) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { trackPageVisibility } from '@withease/web-api'; import { createEvent, sample } from 'effector'; const setup = createEvent(); const teardown = createEvent(); const visibility = trackPageVisibility({ setup, teardown }); setup(); // Reactive visibility state console.log(visibility.$visible.getState()); // true if page is visible console.log(visibility.$hidden.getState()); // true if page is hidden // Pause/resume operations based on visibility sample({ clock: visibility.hidden, fn: () => console.log('Page hidden - pausing animations'), }); sample({ clock: visibility.visible, fn: () => console.log('Page visible - resuming animations'), }); ``` ### Response #### Success Response (200) N/A (Returns Effector stores) #### Response Example ```json { "$visible": true, "$hidden": false } ``` ``` -------------------------------- ### Initialize with Static Asynchronous i18next Instance Source: https://github.com/effector/withease/blob/master/apps/website/docs/i18next/index.md Configures the i18next integration with a static asynchronous i18next instance. This approach, similar to the static synchronous method, is less flexible than using replaceable instances but is still viable. The integration is ready to use after the `appStarted` event is triggered. ```ts import i18next from 'i18next'; import { createStore, createEvent } from 'effector'; import { createI18nextIntegration } from '@withease/i18next'; // Event that should be called after application initialization const appStarted = createEvent(); const integration = createI18nextIntegration({ instance: () => i18next.use(/* ... */).init(/* ... */), setup: appStarted, }); ``` -------------------------------- ### trackPreferredLanguages Source: https://context7.com/effector/withease/llms.txt Creates reactive stores for tracking the user's preferred languages based on browser settings. Supports server-side rendering via the Accept-Language header. ```APIDOC ## trackPreferredLanguages(config) ### Description Creates reactive stores for tracking user's preferred languages from browser settings. ### Method N/A (Function call that returns stores) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { trackPreferredLanguages } from '@withease/web-api'; import { createEvent, sample } from 'effector'; const setup = createEvent(); const teardown = createEvent(); const languages = trackPreferredLanguages({ setup, teardown }); setup(); // Primary language console.log(languages.$language.getState()); // e.g., 'en-US' // All preferred languages console.log(languages.$languages.getState()); // e.g., ['en-US', 'en', 'es'] // React to language changes sample({ clock: languages.languageChanged, source: languages.$language, fn: (lang) => console.log(`Language changed to: ${lang}`), }); ``` ### Response #### Success Response (200) N/A (Returns Effector stores) #### Response Example ```json { "$language": "en-US", "$languages": ["en-US", "en", "es"] } ``` ``` -------------------------------- ### Initialize with Static i18next Instance Source: https://github.com/effector/withease/blob/master/apps/website/docs/i18next/index.md Sets up the i18next integration using a static i18next instance. While functional, using replaceable instances is recommended to avoid global state and allow for runtime instance replacement. The integration is activated upon the dispatch of the `appStarted` event. ```ts import i18next from 'i18next'; import { createStore, createEvent } from 'effector'; import { createI18nextIntegration } from '@withease/i18next'; // Event that should be called after application initialization const appStarted = createEvent(); const integration = createI18nextIntegration({ instance: i18next.createInstance(/* ... */), setup: appStarted, }); ``` -------------------------------- ### Explicit Application Start with Scope (Effector) Source: https://github.com/effector/withease/blob/master/apps/website/docs/magazine/fork_api_rules.md Illustrates the method for explicitly starting an Effector application by providing the current Scope to the `allSettled` function. This ensures proper management of Effector's state and execution context. ```typescript import { allSettled } from 'effector'; await allSettled(appStarted, { scope }); ``` -------------------------------- ### Configuring Logger Dependency for Different Environments using Fork API Source: https://github.com/effector/withease/blob/master/apps/website/docs/magazine/dependency_injection.md This set of examples illustrates how to use Effector's `fork` and `allSettled` functions to inject different logger implementations based on the environment. It shows configurations for tests (null logger), server (console.log), and browser (external logging service). ```typescript import { fork, allSettled } from "effector"; describe("app", () => { it("should not log anything", async () => { const scope = fork({ values: [[$logger, null]], }); await allSettled(somethingHappened, { scope }); expect(console.log).not.toBeCalled(); }); }); ``` ```typescript import { fork, allSettled } from "effector"; function handleHttp(req, res) { const scope = fork({ values: [[$logger, console.log]], }); await allSettled(somethingHappened, { scope }); // render the app } ``` ```typescript import { fork, allSettled } from "effector"; const scope = fork({ values: [[$logger, Rollbar.log]], }); await allSettled(somethingHappened, { scope }); ``` -------------------------------- ### TypeScript: Trigger Effector Logic with Explicit Start Event Source: https://github.com/effector/withease/blob/master/apps/website/docs/magazine/explicit_start.md This snippet refactors an Effector application to use an explicit 'appStarted' event to trigger the interval for incrementing a counter. It replaces direct execution of the interval effect with a sample that listens for the 'appStarted' event. This approach provides better control over when the application's core logic begins. ```typescript // app.ts import { createStore, createEvent, sample, scopeBind, createEffect } from 'effector'; const $counter = createStore(0); const increment = createEvent(); const startIncrementationIntervalFx = createEffect(() => { const boundIncrement = scopeBind(increment, { safe: true }); setInterval(() => { boundIncrement(); }, 1000); }); sample({ clock: increment, source: $counter, fn: (counter) => counter + 1, target: $counter, }); // startIncrementationIntervalFx(); // Original direct execution removed const appStarted = createEvent(); // Explicit start event sample({ clock: appStarted, target: startIncrementationIntervalFx }); // Trigger effect on appStarted ``` -------------------------------- ### trackNetworkStatus Source: https://context7.com/effector/withease/llms.txt Creates reactive stores for tracking the online/offline network status of the user's device. It allows for reacting to network changes and syncing data accordingly. ```APIDOC ## trackNetworkStatus(config) ### Description Creates reactive stores for tracking online/offline network status. ### Method N/A (Function call that returns stores) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { trackNetworkStatus } from '@withease/web-api'; import { createEvent, sample } from 'effector'; const setup = createEvent(); const teardown = createEvent(); const network = trackNetworkStatus({ setup, teardown }); setup(); // Reactive network state console.log(network.$online.getState()); // true or false console.log(network.$offline.getState()); // opposite of $online // React to network changes sample({ clock: network.online, fn: () => console.log('Back online! Syncing data...'), }); sample({ clock: network.offline, fn: () => console.log('Gone offline. Switching to cached data...'), }); ``` ### Response #### Success Response (200) N/A (Returns Effector stores) #### Response Example ```json { "$online": true, "$offline": false } ``` ``` -------------------------------- ### Track Screen Orientation with Effector Source: https://context7.com/effector/withease/llms.txt Provides Effector stores for monitoring the device's screen orientation type and rotation angle. It uses setup and teardown events and offers boolean stores for portrait and landscape states. This enables dynamic UI adjustments based on the current screen orientation. ```typescript import { trackScreenOrientation } from '@withease/web-api'; import { createEvent, sample } from 'effector'; const setup = createEvent(); const teardown = createEvent(); const orientation = trackScreenOrientation({ setup, teardown }); setup(); // Orientation type: 'portrait-primary' | 'portrait-secondary' | 'landscape-primary' | 'landscape-secondary' console.log(orientation.$type.getState()); // Rotation angle in degrees console.log(orientation.$angle.getState()); // 0, 90, 180, or 270 // Boolean states for layout decisions console.log(orientation.$portrait.getState()); // true if portrait console.log(orientation.$landscape.getState()); // true if landscape // Adapt UI based on orientation sample({ clock: orientation.$landscape.updates, filter: Boolean, fn: () => console.log('Switched to landscape - adjusting layout'), }); sample({ clock: orientation.$portrait.updates, filter: Boolean, fn: () => console.log('Switched to portrait - adjusting layout'), }); ``` -------------------------------- ### createReduxIntegration Source: https://github.com/effector/withease/blob/master/apps/website/docs/redux/index.md Initializes the Redux integration object, connecting Effector with a Redux store. It can optionally take a setup event to defer initialization. ```APIDOC ## POST createReduxIntegration ### Description Initializes the Redux integration object, connecting Effector with a Redux store. It can optionally take a setup event to defer initialization. ### Method POST ### Endpoint /createReduxIntegration ### Parameters #### Request Body - **reduxStore** (object) - Optional - The Redux store instance. - **setup** (Event) - Required - An Effector event that triggers the initialization, typically an application start event. ``` -------------------------------- ### Track CSS Media Queries with Effector Source: https://context7.com/effector/withease/llms.txt Creates reactive stores for matching CSS media queries. It supports tracking single or multiple media queries and provides setup/teardown events for lifecycle management. It also offers a curried usage pattern. ```typescript import { trackMediaQuery } from '@withease/web-api'; import { createEvent, sample } from 'effector'; const setup = createEvent(); const teardown = createEvent(); // Single media query const darkMode = trackMediaQuery('(prefers-color-scheme: dark)', { setup, teardown }); setup(); console.log(darkMode.$matches.getState()); // true or false based on system preference sample({ clock: darkMode.matched, fn: () => console.log('Dark mode activated!'), }); // Multiple media queries const breakpoints = trackMediaQuery({ mobile: '(max-width: 767px)', tablet: '(min-width: 768px) and (max-width: 1023px)', desktop: '(min-width: 1024px)', }, { setup, teardown }); console.log(breakpoints.mobile.$matches.getState()); // true/false console.log(breakpoints.tablet.$matches.getState()); // true/false console.log(breakpoints.desktop.$matches.getState()); // true/false // Curried usage (returns function) const createDarkModeTracker = trackMediaQuery('(prefers-color-scheme: dark)'); const darkModeResult = createDarkModeTracker({ setup, teardown }); ``` -------------------------------- ### Example Usage in React with Effector-React Source: https://github.com/effector/withease/blob/master/apps/website/docs/factories/index.md Illustrates how to use the invoked factory units ($counter, increment, decrement) within a React component using the `useUnit` hook from `effector-react`. ```jsx import { useUnit } from 'effector-react'; import { $counter, increment, decrement } from './model'; // assuming you've invoked your factory in `model.js`/`model.ts` const CounterComponent = () => { const counter = useUnit($counter); const [onIncrement, onDecrement] = useUnit(increment, decrement); return (

Counter: {counter}

); }; ``` -------------------------------- ### Use `nothing` and `anything` Contracts with @withease/contracts Source: https://context7.com/effector/withease/llms.txt Utilizes special contracts: `nothing` matches `null` or `undefined`, useful for optional fields, and `anything` matches any value. Demonstrates their application in object validation. ```typescript import { nothing, anything, obj, str, or } from '@withease/contracts'; // `nothing` matches null or undefined console.log(nothing.isData(null)); // true console.log(nothing.isData(undefined)); // true console.log(nothing.isData('')); // false // Optional fields in objects const User = obj({ name: str, age: or(num, nothing), // age is optional }); console.log(User.isData({ name: 'Alice' })); // true console.log(User.isData({ name: 'Alice', age: null })); // true // `anything` matches any value console.log(anything.isData('hello')); // true console.log(anything.isData(42)); // true console.log(anything.isData(null)); // true console.log(anything.isData({})); // true ``` -------------------------------- ### Create i18next Integration - Effector i18next Source: https://context7.com/effector/withease/llms.txt Sets up an Effector integration for the i18next internationalization library. It provides reactive stores for language state and translation functions, requiring an initialized i18next instance and setup/teardown events. ```typescript import { createI18nextIntegration } from '@withease/i18next'; import { createEvent, sample } from 'effector'; import i18next from 'i18next'; // Initialize i18next const i18nextInstance = i18next.createInstance(); await i18nextInstance.init({ lng: 'en', resources: { en: { translation: { greeting: 'Hello, {{name}}!', welcome: 'Welcome to our app', items: '{{count}} items', }, }, es: { translation: { greeting: 'Hola, {{name}}!', welcome: 'Bienvenido a nuestra app', items: '{{count}} artículos', }, }, }, }); // Create Effector integration const appStarted = createEvent(); const appStopped = createEvent(); const { $isReady, $language, $t, $instance, translated, changeLanguageFx, reporting, } = createI18nextIntegration({ instance: i18nextInstance, setup: appStarted, teardown: appStopped, }); // Start the app appStarted(); // Use reactive translation stores console.log($isReady.getState()); // true console.log($language.getState()); // 'en' // Create reactive translated strings const $greeting = translated('greeting', { name: createStore('World') }); console.log($greeting.getState()); // 'Hello, World!' // Simple translation without variables const $welcome = translated('welcome'); console.log($welcome.getState()); // 'Welcome to our app' // Change language reactively await changeLanguageFx('es'); console.log($language.getState()); // 'es' console.log($welcome.getState()); // 'Bienvenido a nuestra app' // Listen for missing translation keys sample({ clock: reporting.missingKey, fn: ({ key, namespace }) => console.warn(`Missing key: ${namespace}:${key}`), }); ``` -------------------------------- ### Define Field Optional with Null Value (TypeScript) Source: https://github.com/effector/withease/blob/master/apps/website/docs/contracts/cookbook/optional_fields.md This example shows how to define a field that can be a number or explicitly `null` using `or` and `val(null)` from `@withease/contracts`. The `age` field will accept a number or null. ```typescript import { obj, str, num, or, val } from '@withease/contracts'; const UserWithOptionalAge = obj({ name: str, age: or(num, val(null)), }); ``` -------------------------------- ### Integrate Redux Store with Effector for Testing Source: https://github.com/effector/withease/blob/master/apps/website/docs/redux/index.md This snippet demonstrates how to create a Redux integration with Effector, making the Redux store accessible via `$reduxStore`. This allows for testing Redux logic using Effector's Fork API by providing a mock Redux store instance. ```typescript // app code const myReduxStore = configureStore({ // ... }); const reduxInterop = createReduxIntegration({ reduxStore: myReduxStore, setup: appStarted, }); // user model const $user = combine(reduxInterop.$state, (x) => x.user); const updateUserName = reduxInterop.dispatch.prepend((name: string) => userSlice.changeName(name) ); sample({ clock: saveButtonClicked, source: $nextName, target: updateUserName, }); ``` ```typescript test('username updated after save button click', async () => { const mockStore = configureStore({ // ... }); const scope = fork({ values: [ // Providing mock version of the redux store [reduxInterop.$reduxStore, mockStore], // Mocking anything else, if needed [$nextName, 'updated'], ], }); await allSettled(appStarted, { scope }); expect(scope.getState($userName)).toBe('initial'); await allSettled(saveButtonClicked, { scope }); expect(scope.getState($userName)).toBe('updated'); }); ``` -------------------------------- ### Literal Value Validation with val() in @withease/contracts Source: https://context7.com/effector/withease/llms.txt Shows how to use the `val()` function from `@withease/contracts` to create contracts that validate against a specific literal value. Examples include validating the number 42 and the string 'active'. ```typescript import { val } from '@withease/contracts'; const only42 = val(42); console.log(only42.isData(42)); // true console.log(only42.isData(43)); // false console.log(only42.getErrorMessages(43)); // ['expected 42, got 43'] const statusActive = val('active'); console.log(statusActive.isData('active')); // true console.log(statusActive.isData('inactive')); // false ``` -------------------------------- ### Track Page Visibility with Effector Source: https://context7.com/effector/withease/llms.txt Generates Effector stores to track the visibility state of the web page (visible or hidden). It uses setup and teardown events for listener management and provides stores for visible/hidden states and corresponding events. This is useful for pausing or resuming operations like animations or polling when the tab is not active. ```typescript import { trackPageVisibility } from '@withease/web-api'; import { createEvent, sample, createStore, createEffect } from 'effector'; const setup = createEvent(); const teardown = createEvent(); const visibility = trackPageVisibility({ setup, teardown }); setup(); // Reactive visibility state console.log(visibility.$visible.getState()); // true if page is visible console.log(visibility.$hidden.getState()); // true if page is hidden // Pause/resume operations based on visibility sample({ clock: visibility.hidden, fn: () => console.log('Page hidden - pausing animations'), }); sample({ clock: visibility.visible, fn: () => console.log('Page visible - resuming animations'), }); // Common use case: pause polling when tab is hidden const pollDataFx = createEffect(async () => { // fetch data }); const $shouldPoll = createStore(true) .on(visibility.hidden, () => false) .on(visibility.visible, () => true); sample({ clock: pollDataFx.done, filter: $shouldPoll, target: pollDataFx, }); ```