### Install Dependencies and Start Server Source: https://github.com/effector/effector/blob/master/documentation/README.md Install project dependencies using pnpm and start the development server. Ensure pnpm is installed globally. ```shell pnpm install pnpm start ``` -------------------------------- ### Run Effector React Native Example on iOS Simulator Source: https://github.com/effector/effector/blob/master/examples/effector-react-native-example/README.md Navigate to the ios directory, install dependencies with pod install, and then run the app on the simulator. ```bash cd ios/ && pod install && cd ../ react-native run-ios ``` -------------------------------- ### Install `effector-action` and `patronum` packages Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/essentials/unit-composition.mdx Install the necessary packages for using `createAction` and other related utilities. ```bash npm install effector-action patronum ``` ```bash yarn install effector-action patronum ``` ```bash pnpm install effector-action patronum ``` -------------------------------- ### Start Search Development Server Source: https://github.com/effector/effector/blob/master/documentation/README.md Start the search development server after building the documentation. This server is required for the search functionality to work locally. ```shell pnpm search:dev ``` -------------------------------- ### Install Effector and Effector-Solid Source: https://github.com/effector/effector/blob/master/packages/effector-solid/README.md Install the necessary packages for effector and effector-solid using npm, yarn, or pnpm. ```bash npm install --save effector effector-solid ``` ```bash yarn add effector effector-solid ``` ```bash pnpm add effector effector-solid ``` -------------------------------- ### Build Project with Yarn Source: https://github.com/effector/effector/blob/master/examples/react-ssr/README.md Installs dependencies and builds the project using Yarn. Ensure you have Yarn installed. ```sh yarn && yarn build ``` -------------------------------- ### Start Astro with Search Enabled Source: https://github.com/effector/effector/blob/master/documentation/README.md Start the Astro development server with the PUBLIC_SEARCH environment variable set to true to enable the search functionality. ```shell PUBLIC_SEARCH=true pnpm dev ``` -------------------------------- ### Basic useEvent example Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector-vue/useEvent.mdx This example demonstrates how to use the useEvent hook to bind an event to a store's update handler in a Vue component setup function. It's intended for SSR environments. ```javascript import { createStore, createEvent } from "effector"; import { useEvent } from "effector-vue/ssr"; const incremented = createEvent(); const $count = createStore(0); $count.on(incremented, (x) => x + 1); export default { setup() { const counter = useStore($count); const onIncrement = useEvent(incremented); return { onIncrement, counter, }; }, }; ``` -------------------------------- ### Start Server with GitHub Token Source: https://github.com/effector/effector/blob/master/documentation/README.md Start the development server with a GitHub Personal Access Token for fetching commit history. Replace REDACTED_TOKEN with your actual token. ```shell GITHUB_TOKEN=github_pat_REDACTED_TOKEN pnpm start ``` -------------------------------- ### Usage Example for Countdown Timer Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/recipes/common/countdown.mdx Shows how to use the `createCountdown` function. It involves creating start and abort events, initializing the countdown, watching for ticks, and manually starting and aborting the timer. ```javascript const startCountdown = createEvent(); const abortCountdown = createEvent(); const countdown = createCountdown("simple", { start: startCountdown, abort: abortCountdown, }); // handle each tick countdown.tick.watch((remainSeconds) => { console.info("Tick. Remain seconds: ", remainSeconds); }); // let's start startCountdown(15); // 15 ticks to count down, 1 tick per second // abort after 5 second setTimeout(abortCountdown, 5000); ``` -------------------------------- ### Basic Test Setup with Fork Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/guides/testing.mdx Demonstrates a basic unit test setup using `fork` to create an isolated scope. It verifies initial state, simulates an event, and checks the final state. ```typescript import { fork, allSettled } from "effector"; import { $clicksCount, buttonClicked, validateClickFx } from "./model"; test("main case", async () => { const scope = fork(); // 1 expect(scope.getState($clicksCount)).toEqual(0); // 2 await allSettled(buttonClicked, { scope }); // 3 expect(scope.getState($clicksCount)).toEqual(1); // 4 }); ``` -------------------------------- ### Start Server with Yarn Source: https://github.com/effector/effector/blob/master/examples/react-ssr/README.md Starts the server after the project has been built. This command assumes the build process was successful. ```sh yarn start ``` -------------------------------- ### Example of Local Factory Configuration Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector/swc-plugin.mdx Demonstrates configuring a local factory located at './src/factory' using the SWC plugin. ```json ["@effector/swc-plugin", { "factories": ["./src/factory"] }] ``` ```typescript import { createStore } from "effector"; /* createBooleanStore is a factory */ export const createBooleanStore = () => createStore(true); ``` ```typescript import { createBooleanStore } from "../factory"; const $boolean = createBooleanStore(); /* Treated as a factory! */ ``` -------------------------------- ### Basic Store Usage Example Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector/createStore.mdx Demonstrates basic store creation and manipulation using createEvent, createStore, .on, .reset, .map, and .watch. ```javascript import { createEvent, createStore } from "effector"; const addTodo = createEvent(); const clearTodos = createEvent(); const $todos = createStore([]) .on(addTodo, (todos, newTodo) => [...todos, newTodo]) .reset(clearTodos); const $selectedTodos = $todos.map((todos) => { return todos.filter((todo) => !!todo.selected); }); $todos.watch((todos) => { console.log("todos", todos); }); ``` -------------------------------- ### Install Effector with React Support Source: https://github.com/effector/effector/blob/master/README.md Install Effector along with the effector-react integration package for seamless use within React applications. Refer to the official documentation for detailed setup instructions. ```bash npm install effector effector-react ``` -------------------------------- ### Complete Example: Counter with Backend Validation Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/guides/testing.mdx Demonstrates a complete Effector setup for a counter that includes asynchronous backend validation before incrementing. It uses `createEvent`, `createStore`, `createEffect`, and `sample` to manage the state transitions based on user actions and API responses. ```typescript import { createEvent, createStore, createEffect, sample } from "effector"; export const buttonClicked = createEvent(); export const validateClickFx = createEffect(async () => { /* external API call */ }); export const $clicksCount = createStore(0); sample({ clock: buttonClicked, source: $clicksCount, filter: (count) => count < 100, target: validateClickFx, }); sample({ clock: validateClickFx.done, source: $clicksCount, fn: (count) => count + 1, target: $clicksCount, }); sample({ clock: validateClickFx.fail, fn: () => 0, target: $clicksCount, }); ``` -------------------------------- ### Effector Feature Integration Example Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/explanation/sids.mdx Demonstrates how to create and manage stores and events for different features (first name, last name, form) and integrate them using `combine` and `sample`. This setup allows for decoupled feature logic that can be triggered from anywhere. ```tsx // src/features/first-name/model.ts import { createStore, createEvent } from "effector"; export const firstNameChanged = createEvent(); export const $firstName = createStore(""); $firstName.on(firstNameChanged, (_, firstName) => firstName); // src/features/last-name/model.ts import { createStore, createEvent } from "effector"; export const lastNameChanged = createEvent(); export const $lastName = createStore(""); $lastName.on(lastNameChanged, (_, lastName) => lastName); // src/features/form/model.ts import { createEvent, sample, combine } from "effector"; import { $firstName, firstNameChanged } from "@/features/first-name"; import { $lastName, lastNameChanged } from "@/features/last-name"; export const formValuesFilled = createEvent<{ firstName: string; lastName: string }>(); export const $fullName = combine($firstName, $lastName, (first, last) => `${first} ${last}`); sample({ clock: formValuesFilled, fn: (values) => values.firstName, target: firstNameChanged, }); sample({ clock: formValuesFilled, fn: (values) => values.lastName, target: lastNameChanged, }); ``` -------------------------------- ### Install Effector and Effector-React Source: https://github.com/effector/effector/blob/master/packages/effector-react/README.md Install the necessary packages for Effector and its React bindings using npm or yarn. ```bash npm install --save effector effector-react ``` ```bash yarn add effector effector-react ``` -------------------------------- ### Basic Media Query Listener Source: https://github.com/effector/effector/blob/master/recipes/media-queries/README.md A standard JavaScript example of how to listen for media query changes using `window.matchMedia` and its `addListener` method. This is a foundational example before integrating with Effector. ```js const mediaQueryList = window.matchMedia('(orientation: portrait)') mediaQueryList.addListener(e => { if (e.matches) { // The viewport is currently in portrait orientation } else { // The viewport is currently in landscape orientation } }) ``` -------------------------------- ### Basic useList Example Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector-react/useList.mdx Render a list of users from an Effector store. `useList` automatically handles keys, so they don't need to be specified manually. ```jsx import { createStore } from "effector"; import { useList } from "effector-react"; const $users = createStore([ { id: 1, name: "Yung" }, { id: 2, name: "Lean" }, { id: 3, name: "Kyoto" }, { id: 4, name: "Sesh" }, ]); const App = () => { // we don't need keys here any more const list = useList($users, ({ name }, index) => (
  • [{index}] {name}
  • )); return ; }; ``` -------------------------------- ### Basic useUnit Example Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector-react/useUnit.mdx Demonstrates the basic usage of useUnit to access a store and multiple events. Requires `effector` and `effector-react`. ```jsx import { createStore, createEvent, fork } from "effector"; import { useUnit, Provider } from "effector-react"; const incremented = createEvent(); const decremented = createEvent(); const $count = createStore(0); $count.on(incremented, (count) => count + 1); $count.on(decremented, (count) => count - 1); const App = () => { const count = useUnit($count); const on = useUnit({ incremented, decremented }); // or const [a, b] = useUnit([incremented, decremented]); return ( <>

    Count: {count}

    ); }; const scope = fork(); render( () => ( ), document.getElementById("root"), ); ``` -------------------------------- ### Install Effector with SolidJS Support Source: https://github.com/effector/effector/blob/master/README.md Install Effector and the effector-solid integration package for use with SolidJS applications. ```bash npm install effector effector-solid ``` -------------------------------- ### Split method examples Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector/split.mdx Demonstrates various ways to use the split method with case functions, case stores, matcher functions, and matcher stores. ```typescript split({ source, match, cases }); ``` ```typescript split({ source: Unit // case function match: (data: T) => 'a' | 'b', cases: { a: Unit | Unit[], b: Unit | Unit[], __?: Unit | Unit[] } }) split({ source: Unit // case store match: Store<'a' | 'b'>, cases: { a: Unit | Unit[], b: Unit | Unit[], __?: Unit | Unit[] } }) split({ source: Unit match: { // matcher function a: (data: T) => boolean, // matcher store b: Store }, cases: { a: Unit | Unit[], b: Unit | Unit[], __?: Unit | Unit[] } }) ``` -------------------------------- ### Store Immutability Example Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector/Store.mdx Demonstrates correct and incorrect ways to update store state immutably. ```APIDOC ## Store Immutability Examples ### Correct Immutability This approach ensures the store updates because a new array reference is created: ```ts $items.on(addItem, (items, newItem) => { const updatedItems = [...items]; // ✅ .push method is called on a new array updatedItems.push(newItem); return updatedItems; }); ``` ### Incorrect Immutability This approach will **not** update the store because the array reference remains the same: ```ts $items.on(addItem, (items, newItem) => { // ❌ Error! The array reference remains the same, the store will not be updated items.push(newItem); return items; }); ``` Updating objects works in a similar way. A store in effector should be as small as possible, responsible for a specific part of the business logic. ``` -------------------------------- ### Basic useStoreMap Example for User Data Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector-react/useStoreMap.mdx This example demonstrates using useStoreMap to efficiently retrieve and display individual user data from a list of users stored in an Effector store. It uses the `keys` option to ensure the selector function only re-runs when the specific user ID changes. ```jsx import { createStore } from "effector"; import { useList, useStoreMap } from "effector-react"; const usersRaw = [ { id: 1, name: "Yung", }, { id: 2, name: "Lean", }, { id: 3, name: "Kyoto", }, { id: 4, name: "Sesh", }, ]; const $users = createStore(usersRaw); const $ids = createStore(usersRaw.map(({ id }) => id)); const User = ({ id }) => { const user = useStoreMap({ store: $users, keys: [id], fn: (users, [userId]) => users.find(({ id }) => id === userId) ?? null, }); return (
    [{user.id}] {user.name}
    ); }; const UserList = () => { return useList($ids, (id) => ); }; ``` -------------------------------- ### Combine single store with numerical transformation example Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector/combine.mdx Example showing how to combine a store containing a price and apply a transformation to calculate the price with tax. The derived store reflects the updated price. ```typescript import { createStore, combine } from "effector"; const $price = createStore(100); const $priceWithTax = combine($price, (price) => price * 1.2); $priceWithTax.watch((price) => console.log("Price with tax:", price)); ``` -------------------------------- ### Basic Split Example Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector/split.mdx Demonstrates a basic usage of `split` with named cases based on event payload properties. ```APIDOC ## Basic Split Example ### Description This example shows how to use the `split` method to divide an event stream into multiple streams based on the properties of the event payload. It includes handling for specific authors and a default case for any other input. ### Method `split(event, { case1: condition1, case2: condition2, ... })` ### Endpoint N/A (Client-side JavaScript library) ### Parameters #### Event - **event** (Event) - The event to be split. #### Cases - **caseName** (Function) - A function that returns true if the event should be routed to this case. ### Request Example ```javascript import { createEvent, split } from "effector"; const message = createEvent(); const messageByAuthor = split(message, { bob: ({ user }) => user === "bob", alice: ({ user }) => user === "alice", }); messageByAuthor.bob.watch(({ text }) => { console.log("[bob]: ", text); }); messageByAuthor.alice.watch(({ text }) => { console.log("[alice]: ", text); }); message({ user: "bob", text: "Hello" }); message({ user: "alice", text: "Hi bob" }); /* default case, triggered if no one condition met */ const { __: guest } = messageByAuthor; guest.watch(({ text }) => { console.log("[guest]: ", text); }); message({ user: "unregistered", text: "hi" }); ``` ### Response #### Success Response (Event Streams) - **caseName** (Event) - An event stream that is triggered when the corresponding condition is met. - **__** (Event) - The default event stream, triggered when no other conditions are met. #### Response Example ``` [bob]: Hello [alice]: Hi bob [guest]: hi ``` ``` -------------------------------- ### guard with Clock, Source, Filter, and Target Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector/guard.mdx This example demonstrates the basic usage of `guard` with all its primary parameters: `clock`, `source`, `filter`, and `target`. ```APIDOC ## POST /api/users ### Description This endpoint allows for the creation of a new user in the system. It requires user details in the request body and returns the created user's information upon success. ### Method POST ### Endpoint `/api/users` ### Parameters #### Request Body - **username** (string) - Required - The desired username for the new user. - **email** (string) - Required - The email address of the new user. - **password** (string) - Required - The password for the new user. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com", "password": "securepassword123" } ``` ### Response #### Success Response (201) - **id** (string) - The unique identifier for the newly created user. - **username** (string) - The username of the created user. - **email** (string) - The email address of the created user. #### Response Example ```json { "id": "user-12345", "username": "johndoe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Combine single store with transformation example Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector/combine.mdx Example demonstrating how to combine a single store and transform its value to create a greeting message. The derived store updates automatically when the source store changes. ```typescript import { createStore, combine } from "effector"; const $name = createStore("John"); const $greeting = combine($name, (name) => `Hello, ${name} દૂર!`); $greeting.watch((greeting) => console.log(greeting)); ``` -------------------------------- ### Example of using useStore in a React component Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector-react/useStore.mdx This example demonstrates how to use the useStore hook to display and update a counter value in a React component. It also shows the usage of useEvent for handling events. ```jsx import { createStore } from "effector"; import { useStore, useEvent } from "effector-react"; const $counter = createStore(0); const { incrementClicked, decrementClicked } = createApi($counter, { incrementClicked: (state) => state + 1, decrementClicked: (state) => state - 1, }); const App = () => { const counter = useStore($counter); const [onIncrement, onDecrement] = useEvent([incrementClicked, decrementClicked]); return (
    {counter}
    ); }; ``` -------------------------------- ### Custom Serialize Configuration Example Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector/createStore.mdx Illustrates how to use a custom `serialize` configuration for a store to handle Date objects correctly during SSR hydration. ```typescript import { createEvent, createStore, serialize, fork, allSettled } from "effector"; const saveDate = createEvent(); const $date = createStore(null, { // Date objects are automatically converted to ISO date strings when calling JSON.stringify // but are not converted back to Date when calling JSON.parse – the result will be the same ISO date string // This will cause state mismatch when hydrating state on the client during server-side rendering // // Custom `serialize` configuration solves this problem serialize: { write: (dateOrNull) => (dateOrNull ? dateOrNull.toISOString() : dateOrNull), read: (isoStringOrNull) => (isoStringOrNull ? new Date(isoStringOrNull) : isoStringOrNull), }, }).on(saveDate, (_, p) => p); const serverScope = fork(); await allSettled(saveDate, { scope: serverScope, params: new Date() }); const serverValues = serialize(serverScope); // `serialize.write` for store `$date` was called console.log(serverValues); // => { nq1e2rb: "2022-11-05T15:38:53.108Z" } // Date object from store saved as ISO date const clientScope = fork({ values: serverValues }); // `serialize.read` for store `$date` was called const currentDate = clientScope.getState($date); console.log(currentDate); // => Date 11/5/2022, 10:40:13 PM // ISO date string converted back to Date object ``` -------------------------------- ### Create a Gate with Configuration Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector-solid/createGate.mdx Use createGate with a configuration object to set default state, domain, and a component name. This is useful for more complex setups. ```typescript createGate(config): Gate ``` -------------------------------- ### Deploy Serverless Application Source: https://github.com/effector/effector/blob/master/examples/serverless-ssr/README.md Installs dependencies and deploys the serverless application to AWS Lambda using the serverless framework. Ensure you have configured your domain and certificate in `domain.json`. ```sh yarn && yarn deploy ``` -------------------------------- ### Effector React Integration Example Source: https://github.com/effector/effector/blob/master/recipes/media-queries/README.md An incomplete example showing the import of `useUnit` from `effector-react` and `screenQueries` from a local module. This snippet is intended to demonstrate the setup for connecting Effector stores to React components. ```js import {useUnit} from 'effector-react' import {screenQueries} from './screenQueries' ``` -------------------------------- ### Vue Counter Component with useUnit Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/introduction/get-started.mdx Shows how to use Effector's `useUnit` hook within a Vue.js composition API setup. Provides examples of destructuring state and event handlers from the hook. ```html ``` -------------------------------- ### Basic Gate Usage Example Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector-solid/createGate.mdx Demonstrates the basic usage of createGate in a SolidJS application. It shows how to create a gate, render it with props, watch its state, and observe state changes on mount and unmount. ```javascript import { createGate } from "effector-solid"; import { render } from "solid-js/web"; const Gate = createGate("gate with props"); const App = () => (
    ); Gate.state.watch((state) => { console.log("current state", state); }); // => current state {} const unmount = render(() => , document.getElementById("root")); // => current state {foo: 'bar'} unmount(); // => current state {} ``` -------------------------------- ### Build Documentation for Search Source: https://github.com/effector/effector/blob/master/documentation/README.md Build the documentation with compression disabled to speed up the build process, which is necessary for enabling the search functionality. ```shell COMPRESS=false pnpm build ``` -------------------------------- ### Vite Configuration for Effector Babel Plugin Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector/babel-plugin.mdx Example `vite.config.js` setup to integrate the `effector/babel-plugin`. Ensure `babelrc` and `configFile` are set to `true` to allow the plugin to be picked up from your project's Babel configuration. ```javascript // vite.config.js import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; export default defineConfig({ plugins: [ react({ babel: { plugins: ["effector/babel-plugin"], // Use .babelrc files babelrc: true, // Use babel.config.js files configFile: true, }, }), ], }); ``` -------------------------------- ### VueEffector Plugin Installation Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector-vue/VueEffectorVue2.mdx This snippet shows how to install the VueEffector plugin using Vue.use(). ```APIDOC ## VueEffector Plugin Installation ### Description Installs the VueEffector plugin for Vue 2. ### Method `Vue.use()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```js import Vue from "vue"; import { VueEffector } from "effector-vue"; Vue.use(VueEffector); ``` ### Response #### Success Response (200) Void #### Response Example None ``` -------------------------------- ### Basic sample usage Source: https://context7.com/effector/effector/llms.txt Connects units by taking data from a source when a clock triggers. Use this for building reactive data flows. ```javascript import { createEvent, createStore, createEffect, sample } from "effector"; const submitForm = createEvent(); const $formData = createStore({ email: "", password: "" }); const $isValid = createStore(false); const loginFx = createEffect(async (data) => { const response = await fetch("/api/login", { method: "POST", body: JSON.stringify(data), }); return response.json(); }); // Basic sample: when submitForm triggers, take $formData and send to loginFx sample({ clock: submitForm, source: $formData, target: loginFx, }); ``` -------------------------------- ### Install VueEffector Plugin Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector-vue/VueEffector.mdx Install the VueEffector plugin into your Vue 3 application instance. ```javascript import { createApp } from "vue"; import { VueEffector } from "effector-vue/options-vue3"; import App from "./App.vue"; const app = createApp(App); app.use(VueEffector); ``` -------------------------------- ### Basic Domain History Example Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector/Domain.mdx Demonstrates how units created within a domain are added to the respective sets in `domain.history`. The output shows the sets containing the created event and store. ```javascript import { createDomain } from "effector"; const domain = createDomain(); const eventA = domain.event(); const $storeB = domain.store(0); console.log(domain.history); // => {stores: Set{storeB}, events: Set{eventA}, domains: Set, effects: Set} ``` -------------------------------- ### Install Effector and Effector-Vue Source: https://github.com/effector/effector/blob/master/packages/effector-vue/README.md Install the necessary Effector and effector-vue packages using npm or yarn. ```bash npm install --save effector effector-vue ``` ```bash yarn add effector effector-vue ``` -------------------------------- ### Basic useGate Example Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector-solid/useGate.mdx Demonstrates how to use the useGate hook to connect a component's props to an Effector Gate. The Gate's state can then be watched for changes. ```jsx import { createGate, useGate } from "effector-solid"; import { Route, Routes } from "solid-app-router"; const PageGate = createGate("page"); const Home = (props) => { useGate(PageGate, props); return
    Home
    ; }; PageGate.state.watch(({ match }) => { console.log(match); }); const App = ( } /> ); ``` -------------------------------- ### VueEffector Plugin Installation Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector-vue/VueEffector.mdx This snippet shows how to install the VueEffector plugin globally in your Vue 3 application. ```APIDOC ## VueEffector Plugin Installation ### Description Installs the `VueEffector` plugin globally into a Vue 3 application. ### Method `app.use(VueEffector)` ### Endpoint N/A (Global Plugin Installation) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```js import { createApp } from "vue"; import { VueEffector } from "effector-vue/options-vue3"; import App from "./App.vue"; const app = createApp(App); app.use(VueEffector); ``` ### Response #### Success Response (200) N/A (Plugin installation does not return a value) #### Response Example N/A ``` -------------------------------- ### Install Effector with Vue Support Source: https://github.com/effector/effector/blob/master/README.md Install Effector and the effector-vue integration package for use with Vue.js applications. ```bash npm install effector effector-vue ``` -------------------------------- ### Create a basic store Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/essentials/manage-states.mdx Defines a store with author information including name and songs. ```typescript import { createStore } from "effector"; const $author = createStore({ name: "Hanz Zimmer", songs: [ { title: "Time", likes: 123 }, { title: "Cornfield Chase", likes: 97 }, { title: "Dream is Collapsing", likes: 33 }, ], }); ``` -------------------------------- ### Install Effector with pnpm Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/introduction/get-started.mdx Use pnpm to install the Effector library. pnpm is a fast, disk-space-efficient package manager. ```bash pnpm install effector ``` -------------------------------- ### sample API Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector/sample.mdx The `sample` method is used to connect units, taking data from a `source` and sending it to a `target` when a `clock` occurs. It's useful for processing events with store data without direct state access. ```APIDOC ## POST /api/sample ### Description Connects units to transfer data from a source to a target when a clock triggers, with optional filtering and transformation. ### Method POST ### Endpoint /api/sample ### Parameters #### Request Body - **clock** (Unit | Unit[]) - Optional - A trigger unit that determines when to sample the source. Can be an Event, Store, Effect, or an array of units. - **source** (Unit) - Required if clock is not provided - The unit from which to read data. - **filter** (fn | Store) - Optional - A predicate function or a store that determines if processing should continue. - **fn** ((sourceValue, eventValue) => transformedValue) - Optional - A transformation function to modify the data before sending it to the target. - **target** (Unit) - Optional - The unit to which the processed data will be sent. If not provided, a new unit is created. - **batch** (boolean) - Optional - Flag for batching updates. - **name** (string) - Optional - Name for the created unit. ### Request Example ```json { "clock": "event", "source": "$store", "target": "$derivedStore", "fn": "(sourceValue, eventValue) => sourceValue + eventValue" } ``` ### Response #### Success Response (200) - **Unit** (Unit) - The target unit, either provided or newly created. #### Response Example ```json { "unitType": "Store", "unitName": "derivedStore" } ``` ``` -------------------------------- ### Install Effector with yarn Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/introduction/get-started.mdx Use yarn to install the Effector library. Yarn is an alternative package manager for Node.js. ```bash yarn install effector ``` -------------------------------- ### Create an Event and Subscribe with Sample Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/essentials/events.mdx Create an event using `createEvent` and subscribe to it using `sample`. The `sample` operator listens for the event via the `clock` argument and executes the specified logic when the event triggers. ```typescript import { sample, createEvent } from "effector"; const event = createEvent(); sample({ clock: event, // ... }); ``` -------------------------------- ### Install Effector SWC Plugin with pnpm Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector/swc-plugin.mdx Install the Effector SWC plugin as a development dependency using pnpm. ```bash pnpm install --save-dev @effector/swc-plugin ``` -------------------------------- ### Install Effector SWC Plugin with yarn Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector/swc-plugin.mdx Install the Effector SWC plugin as a development dependency using yarn. ```bash yarn add --dev @effector/swc-plugin ``` -------------------------------- ### Install Effector SWC Plugin with npm Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector/swc-plugin.mdx Install the Effector SWC plugin as a development dependency using npm. ```bash npm install --save-dev @effector/swc-plugin ``` -------------------------------- ### Sample method arguments Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector/sample.mdx Illustrates the full form of the `sample` method with optional arguments: `clock`, `source`, `filter`, `fn`, `target`, `batch`, and `name`. ```typescript sample({ clock?, source?, filter?, fn?, target?, batch?, name? }) ``` -------------------------------- ### Install VueEffector Plugin Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector-vue/VueEffectorVue2.mdx Install the VueEffector plugin using Vue.use(). This makes the plugin available throughout your Vue 2 application. ```javascript import Vue from "vue"; import { VueEffector } from "effector-vue"; Vue.use(VueEffector); ``` -------------------------------- ### Install Effector Core Package Source: https://github.com/effector/effector/blob/master/README.md Install the core Effector library using npm. This is the foundational package for managing state and events. ```bash npm install effector ``` -------------------------------- ### Install Effector Model Package Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/essentials/dynamic-models.mdx Installs the Effector model package using npm. This package provides the core functionality for dynamic models. ```bash npm install @effector/model ``` -------------------------------- ### Create and Update a Store with Events Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/essentials/manage-states.mdx Demonstrates creating a store with an initial value and updating it reactively when a specific event is triggered. Use this to manage simple state changes. ```typescript import { createStore, createEvent } from "effector"; const $counter = createStore(0); const incremented = createEvent(); // when incremented triggered, increase the counter by 1 $counter.on(incremented, (counterValue) => counterValue + 1); incremented(); // $counter = 1 incremented(); // $counter = 2 ``` -------------------------------- ### Derived store and event creation with sample Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector/sample.mdx Demonstrates creating a derived store when both `clock` and `source` are stores, and a derived event when the `clock` is an event and `source` is a store. ```typescript const event = createEvent(); const $store = createStore(); const $secondStore = createStore(); const $derivedStore = sample({ clock: $store, source: $secondStore, }); // Returns a derived store because both clock and source are stores const derivedEvent = sample({ clock: event, source: $store, }); // Returns a derived event because the clock is an event ``` -------------------------------- ### Create a basic store Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector/Store.mdx Import and create a new store using `createStore`. Stores hold state and update when a new value is strictly not equal to the current one. ```typescript import { type Store, type StoreWritable, createStore } from "effector"; const $store = createStore(); ``` -------------------------------- ### Forest Usage Example Source: https://github.com/effector/effector/blob/master/packages/forest/README.md An example demonstrating how to use Effector Forest to create a reactive form with input fields, a submit button, and real-time form state display. ```APIDOC ## Usage Example This example demonstrates how to integrate Effector Forest into a web application to build a reactive form. ### Code ```javascript import {createStore, createEvent, sample} from 'effector' import {using, spec, h} from 'forest' using(document.body, () => { const {change, submit, $fields} = formModel() h('section', () => { spec({style: {width: '15em'}}) h('form', () => { spec({ handler: { config: {prevent: true}, on: {submit}, }, style: { display: 'flex', flexDirection: 'column', }, }) h('input', { attr: {placeholder: 'Username'}, handler: {input: change('username')}, }) h('input', { attr: {type: 'password', placeholder: 'Password'}, classList: ['w-full', 'py-2', 'px-4'], handler: {input: change('password')}, }) h('button', { text: 'Submit', attr: { disabled: $fields.map( fields => !(fields.username && fields.password), ), }, }) }) h('section', () => { spec({style: {marginTop: '1em'}}) h('div', {text: 'Reactive form debug:'}) h('pre', {text: $fields.map(stringify)}) }) }) }) function formModel() { const changed = createEvent() const submit = createEvent() const $fields = createStore({}).on(changed, (fields, {name, value}) => ({ ...fields, [name]: value, })) const change = name => changed.prepend(e => ({name, value: e.target.value})) sample({ source: $fields, clock: submit, fn: stringify, }).watch(alert) return {change, submit, $fields} } function stringify(values) { return JSON.stringify(values, null, 2) } ``` [Try it](https://share.effector.dev/e2FuOsag) ``` -------------------------------- ### Example: Selecting User by ID with useStoreMap Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector-solid/useStoreMap.mdx Demonstrates using useStoreMap to efficiently select and display user data from a large store based on their ID. It utilizes a selector function that finds the user matching the provided ID. ```jsx import { createStore } from "effector"; import { useUnit, useStoreMap } from "effector-solid"; import { For } from "solid-js/web"; const usersRaw = [ { id: 1, name: "Yung", }, { id: 2, name: "Lean", }, { id: 3, name: "Kyoto", }, { id: 4, name: "Sesh", }, ]; const $users = createStore(usersRaw); const $ids = createStore(usersRaw.map(({ id }) => id)); const User = ({ id }) => { const user = useStoreMap({ store: $users, keys: [id], fn: (users, [userId]) => users.find(({ id }) => id === userId) ?? null, }); return (
    [{user()?.id}] {user()?.name}
    ); }; const UserList = () => { const ids = useUnit($ids); return {(id) => }; }; ``` -------------------------------- ### Create Stores with Initial Values and Types Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/essentials/manage-states.mdx Demonstrates how to create Effector stores using `createStore`, providing initial values and explicit type annotations for better type safety. ```typescript import { createStore } from "effector"; // creating a store with an initial value const $counter = createStore(0); // and with explicit typing const $user = createStore<{ name: "Bob"; age: 25 } | null>(null); const $posts = createStore([]); ``` -------------------------------- ### Common Domain Setup for Worker RPC Source: https://github.com/effector/effector/blob/master/examples/worker-rpc/README.md Defines the Effector domain and a shared effect used for communication between client and worker. This setup is essential for both sides to recognize the communication channel. ```typescript import {createDomain} from 'effector' export const api = createDomain() export const exampleEffect = api.effect() ``` -------------------------------- ### Create and Use Stores Source: https://context7.com/effector/effector/llms.txt Use `createStore` to hold application state. Stores can react to events using `.on()` and derive new stores with `.map()`. ```javascript import { createEvent, createStore } from "effector"; const addTodo = createEvent(); const toggleTodo = createEvent(); const clearTodos = createEvent(); const $todos = createStore([]) .on(addTodo, (todos, newTodo) => [...todos, { text: newTodo, done: false }]) .on(toggleTodo, (todos, index) => todos.map((todo, i) => (i === index ? { ...todo, done: !todo.done } : todo)) ) .reset(clearTodos); // Derived store using .map() const $completedTodos = $todos.map((todos) => todos.filter((todo) => todo.done)); const $todoCount = $todos.map((todos) => todos.length); $todos.watch((todos) => console.log("todos:", todos)); $completedTodos.watch((completed) => console.log("completed:", completed.length)); addTodo("Learn effector"); // => todos: [{ text: 'Learn effector', done: false }] // => completed: 0 toggleTodo(0); // => todos: [{ text: 'Learn effector', done: true }] // => completed: 1 ``` -------------------------------- ### Install Effector Model React Integration Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/essentials/dynamic-models.mdx Installs the Effector model React integration package using npm. This package is required for using dynamic models within React applications. ```bash npm install @effector/model-react ``` -------------------------------- ### Add Explicit App Start with Effector Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/resources/explicit-start.mdx This snippet shows how to refactor an Effector app to include an explicit start event. It uses `createEvent` and `sample` to trigger an interval effect when `appStarted` is called. ```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(); const appStarted = createEvent(); sample({ clock: appStarted, target: startIncrementationIntervalFx, }); ``` -------------------------------- ### Create a Domain Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector/createDomain.mdx Create a new domain, optionally providing a name for debugging purposes. This example shows creating both an unnamed and a named domain, along with associated events, effects, stores, and a nested domain. ```javascript import { createDomain } from "effector"; const domain = createDomain(); // Unnamed domain const httpDomain = createDomain("http"); // Named domain const statusCodeChanged = httpDomain.createEvent(); const downloadFx = httpDomain.createEffect(); const apiDomain = httpDomain.createDomain(); // nested domain const $data = httpDomain.createStore({ status: -1 }); ``` -------------------------------- ### Import sample method Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector/sample.mdx Import the `sample` method from the Effector library. ```typescript import { sample } from "effector"; ``` -------------------------------- ### Update Store with Sample Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/essentials/unit-composition.mdx Use `sample` to update a store by replacing its old value with a new one. This is a straightforward way to manage store state based on events. ```typescript import { createEvent, createStore, sample } from "effector"; const $query = createStore(""); const queryChanged = createEvent(); sample({ clock: queryChanged, target: $query, }); ``` -------------------------------- ### Basic Guard Example Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/api/effector/guard.mdx This example demonstrates a basic usage of `guard`. It triggers `fetchRequest` when `clickRequest` is called, but only if the `$isIdle` store is true. The data passed to `fetchRequest` is the current value of the `$clicks` store. ```javascript import { createStore, createEffect, createEvent, guard } from "effector"; const clickRequest = createEvent(); const fetchRequest = createEffect((n) => new Promise((rs) => setTimeout(rs, 2500, n))); const $clicks = createStore(0).on(clickRequest, (x) => x + 1); const $requestsCount = createStore(0).on(fetchRequest, (x) => x + 1); const $isIdle = fetchRequest.pending.map((pending) => !pending); /* 1. on clickRequest 2. if $isIdle is true 3. take current $clicks value 4. and call fetchRequest with it */ guard({ clock: clickRequest /* 1 */, filter: $isIdle /* 2 */, source: $clicks /* 3 */, target: fetchRequest /* 4 */, }); ``` -------------------------------- ### Correct use of effects and sample for logic Source: https://github.com/effector/effector/blob/master/documentation/src/content/docs/en/guides/best-practices.mdx This sample demonstrates the correct way to handle side effects and logic using `sample` and `createEffect`, avoiding the anti-pattern of using `watch` for logic. ```typescript // separate effects for side effects const saveToStorageFx = createEffect((user: User) => localStorage.setItem('user', JSON.stringify(user)), ); const trackUpdateFx = createEffect((user: User) => api.trackUserUpdate(user)); // connect through sample sample({ clock: $user, target: [saveToStorageFx, trackUpdateFx], }); // for events also use sample sample({ clock: $user, fn: (user) => user.id, target: someEvent, }); ```