### Install @withease/redux with yarn
Source: https://withease.effector.dev/redux
Install the package using yarn.
```sh
yarn add @withease/redux
```
--------------------------------
### Install @withease/web-api with yarn
Source: https://withease.effector.dev/web-api
Install the @withease/web-api package using yarn.
```sh
yarn add @withease/web-api
```
--------------------------------
### Effector App Initialization with Explicit Start
Source: https://effector.dev/en/llms-full.txt
This example demonstrates how to set up an Effector application with an explicit start mechanism. It includes a counter store, an increment event, and an effect to start an interval for incrementing the counter. The `appStarted` event is used to trigger this interval effect.
```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,
});
```
--------------------------------
### Install @withease/web-api with npm
Source: https://withease.effector.dev/web-api
Install the @withease/web-api package using npm.
```sh
npm install @withease/web-api
```
--------------------------------
### Install @withease/redux with pnpm
Source: https://withease.effector.dev/redux
Install the package using pnpm.
```sh
pnpm install @withease/redux
```
--------------------------------
### Install @withease/redux with npm
Source: https://withease.effector.dev/redux
Install the package using npm.
```sh
npm install @withease/redux
```
--------------------------------
### Usage Example for Countdown Timer
Source: https://effector.dev/en/llms-full.txt
Demonstrates how to use the createCountdown function. It shows how to start, abort, and watch for ticks from the countdown timer. Assumes Effector events are available.
```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);
```
--------------------------------
### Example: Logging New Stores with onCreateStore
Source: https://effector.dev/en/llms-full.txt
This example demonstrates using `onCreateStore` to log a message when a new store is created. The callback is invoked for each `createStore` call.
```javascript
import { createDomain } from "effector";
const domain = createDomain();
domain.onCreateStore((store) => {
console.log("new store created");
});
const $a = domain.createStore(null);
// => new store created
```
--------------------------------
### Example of Local Factory Configuration
Source: https://effector.dev/en/llms-full.txt
Demonstrates configuring a local factory using a relative path in the plugin options.
```json
["@effector/swc-plugin", { "factories": ["./src/factory"] }]
```
--------------------------------
### Install @withease/web-api with pnpm
Source: https://withease.effector.dev/web-api
Install the @withease/web-api package using pnpm.
```sh
pnpm install @withease/web-api
```
--------------------------------
### Example: Logging New Domains with onCreateDomain
Source: https://effector.dev/en/llms-full.txt
This example illustrates how to use `onCreateDomain` to log a message when a new subdomain is created. The callback is triggered for each `createDomain` call.
```javascript
import { createDomain } from "effector";
const domain = createDomain();
domain.onCreateDomain((domain) => {
console.log("new domain created");
});
const a = domain.createDomain();
// => new domain created
const b = domain.createDomain();
// => new domain created
```
--------------------------------
### Basic Store Creation
Source: https://effector.dev/en/llms-full.txt
Example of creating a store using `createStore`.
```typescript
const $name = createStore(null);
```
--------------------------------
### Installing effector-action and patronum
Source: https://effector.dev/en/llms-full.txt
Install the `effector-action` and `patronum` packages using npm, yarn, or pnpm to use the `createAction` operator.
```bash
npm install effector-action patronum
```
```bash
yarn install effector-action patronum
```
```bash
pnpm install effector-action patronum
```
--------------------------------
### Sample with Source and Clock
Source: https://effector.dev/en/llms-full.txt
Example of using sample with a source store and a clock event.
```typescript
const clicked = createEvent();
const $store = createStore(0);
const fetchFx = createEffect();
sample($data, clicked);
sample($data, $store);
```
--------------------------------
### Install @withease/factories with yarn
Source: https://withease.effector.dev/factories
Installs the @withease/factories package using the yarn package manager.
```sh
yarn add @withease/factories
```
--------------------------------
### useStoreMap with Keys and DefaultValue Example
Source: https://effector.dev/en/llms-full.txt
Example demonstrating the use of useStoreMap with a configuration object, including keys for dependency tracking and a defaultValue for handling undefined results. This is particularly useful for efficiently rendering lists.
```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) => );
};
```
--------------------------------
### Async Redux Interop Setup
Source: https://withease.effector.dev/magazine/migration_from_redux.html
To avoid cyclic dependencies, use an asynchronous setup for `reduxInterop`. This requires explicit initialization later, potentially involving null-checks if the store isn't ready.
```typescript
// 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);
```
--------------------------------
### Example: Logging New Events with onCreateEvent
Source: https://effector.dev/en/llms-full.txt
This example demonstrates how to use `onCreateEvent` to log a message to the console whenever a new event is created. The callback is invoked for each `createEvent` call.
```javascript
import { createDomain } from "effector";
const domain = createDomain();
domain.onCreateEvent((event) => {
console.log("new event created");
});
const a = domain.createEvent();
// => new event created
const b = domain.createEvent();
// => new event created
```
--------------------------------
### Simple clearNode Example
Source: https://effector.dev/en/llms-full.txt
Demonstrates how to use `clearNode` to destroy a single store. After clearing, the store will no longer react to events.
```javascript
import { createStore, createEvent, clearNode } from "effector";
const inc = createEvent();
const $store = createStore(0).on(inc, (x) => x + 1);
inc.watch(() => console.log("inc called"));
$store.watch((x) => console.log("store state: ", x));
// => store state: 0
inc();
// => inc called
// => store state: 1
clearNode($store);
inc();
// => inc called
```
--------------------------------
### Install @withease/factories with pnpm
Source: https://withease.effector.dev/factories
Installs the @withease/factories package using the pnpm package manager.
```sh
pnpm install @withease/factories
```
--------------------------------
### Effector Model Setup
Source: https://effector.dev/en/llms-full.txt
Defines an event and a store for demonstration purposes.
```javascript
import { createEvent, createStore, fork } from "effector";
const incremented = createEvent();
const $count = createStore(0);
$count.on(incremented, (count) => count + 1);
```
--------------------------------
### Install Effector with npm
Source: https://effector.dev/en/llms-full.txt
Install the Effector library using npm. This is the first step to integrating Effector into your project.
```bash
npm install effector
```
--------------------------------
### Install i18next and @withease/i18next
Source: https://withease.effector.dev/i18next
Install the necessary packages for i18next integration. This includes the i18next library itself and the Effector integration package.
```sh
pnpm install @withease/i18next i18next
```
```sh
yarn add @withease/i18next i18next
```
```sh
npm install @withease/i18next i18next
```
--------------------------------
### Example: Logging New Effects with onCreateEffect
Source: https://effector.dev/en/llms-full.txt
This example shows how to use `onCreateEffect` to log a message when a new effect is created. The callback is triggered for each `createEffect` call.
```javascript
import { createDomain } from "effector";
const domain = createDomain();
domain.onCreateEffect((effect) => {
console.log("new effect created");
});
const fooFx = domain.createEffect();
// => new effect created
const barFx = domain.createEffect();
// => new effect created
```
--------------------------------
### Install @withease/factories with npm
Source: https://withease.effector.dev/factories
Installs the @withease/factories package using the npm package manager.
```sh
npm install @withease/factories
```
--------------------------------
### Async Redux Integration Setup
Source: https://withease.effector.dev/redux
Defer Redux integration object initialization and Redux Store creation. This overload allows passing the Redux Store via a setup event later, which is useful for projects with cyclic dependencies.
```typescript
// 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 Effector with pnpm
Source: https://effector.dev/en/llms-full.txt
Install the Effector library using pnpm. This command is another alternative for package management.
```bash
pnpm install effector
```
--------------------------------
### Custom Factory Implementation Example
Source: https://effector.dev/en/llms-full.txt
A JavaScript example demonstrating how to create a custom factory function `createEffectStatus`. This function takes an effect and creates a store that tracks its status, ensuring unique SIDs when used with the Babel plugin.
```javascript
// ./src/createEffectStatus.js
import { rootDomain } from "./rootDomain";
export function createEffectStatus(fx) {
const $status = rootDomain.createStore("init").on(fx.finally, (_, { status }) => status);
return $status;
}
```
--------------------------------
### Install Effector for Solid
Source: https://effector.dev/en/llms-full.txt
Install the effector and effector-solid packages for SolidJS integration. This provides optimized Effector bindings for Solid's fine-grained reactivity.
```bash
npm install effector effector-solid
```
--------------------------------
### createComponent Example with Effector Stores
Source: https://effector.dev/en/llms-full.txt
Example demonstrating how to create a React component using createComponent with an Effector store. This component displays a counter and allows incrementing it.
```jsx
import { createStore, createEvent } from "effector";
import { createComponent } from "effector-react";
const increment = createEvent();
const $counter = createStore(0).on(increment, (n) => n + 1);
const MyCounter = createComponent($counter, (props, state) => (
Counter: {state}
));
const MyOwnComponent = () => {
// any stuff here
return ;
};
```
--------------------------------
### useStoreMap with Selector Example
Source: https://effector.dev/en/llms-full.txt
Example of using useStoreMap to select and display a specific user from a store of users based on a prop ID. This is useful for large lists.
```javascript
import { createStore } from "effector";
import { useUnit, useStoreMap } from "effector-vue/composition";
const $users = createStore([
{
id: 1,
name: "Yung",
},
{
id: 2,
name: "Lean",
},
{
id: 3,
name: "Kyoto",
},
{
id: 4,
name: "Sesh",
},
]);
export default {
props: {
id: Number,
},
setup(props) {
const user = useStoreMap({
store: $users,
keys: () => props.id,
fn: (users, userId) => users.find(({ id }) => id === userId),
});
return { user };
},
};
```
--------------------------------
### Using a Local Factory
Source: https://effector.dev/en/llms-full.txt
Example showing how to import and use a locally defined factory function in another module.
```typescript
import { createBooleanStore } from "../factory";
const $boolean = createBooleanStore(); /* Treated as a factory! */
```
--------------------------------
### Example: Creating a scope from serialized state
Source: https://effector.dev/en/llms-full.txt
Demonstrates how to initialize a new scope using a pre-existing serialized state object. This is useful for restoring application state.
```typescript
import { fork } from "effector";
const serialized = {
userSid: "alice",
ageSid: 21,
};
const scope = fork({ values: serialized });
```
--------------------------------
### Basic Store Creation and Usage
Source: https://effector.dev/en/llms-full.txt
Demonstrates creating a store for an array of todos, handling additions and resets, and mapping to a derived store. Includes a watcher to log store changes.
```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);
});
```
--------------------------------
### Example: Verifying Effect Implementation
Source: https://effector.dev/en/llms-full.txt
Demonstrates how to use `.use.getCurrent()` to check if the correct handler is assigned to an effect. This is particularly useful in testing scenarios.
```javascript
const handlerA = () => "A";
const handlerB = () => "B";
const fx = createEffect(handlerA);
console.log(fx.use.getCurrent() === handlerA);
// => true
fx.use(handlerB);
console.log(fx.use.getCurrent() === handlerB);
// => true
```
--------------------------------
### Basic useGate Example
Source: https://effector.dev/en/llms-full.txt
Demonstrates how to use the `useGate` hook to pass props to a gate and watch its state changes. Ensure the Gate is created and its state is watched for side effects.
```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 = () => (
} />
);
```
--------------------------------
### useUnit with Store and Event
Source: https://effector.dev/en/llms-full.txt
Use useUnit to get the current value of a store and a function to trigger an event. This example demonstrates binding to a store and an event for UI updates and user interactions.
```jsx
import { createEvent, createStore, fork } from "effector";
import { useUnit, Provider } from "effector-react";
import { render } from "react-dom";
const incrementClicked = createEvent();
const $count = createStore(0);
$count.on(incrementClicked, (count) => count + 1);
const App = () => {
const [count, onIncrement] = useUnit([$count, incrementClicked]);
return (
<>
Count: {count}
>
);
};
const scope = fork();
render(
() => (
),
document.getElementById("root"),
);
```
--------------------------------
### Trigger Navigation from React Component
Source: https://effector.dev/en/llms-full.txt
This example shows how to use the `useUnit` hook in a React component to get a handler for the `navigationTriggered` event, allowing navigation to be initiated directly from component interactions like button clicks.
```javascript
'use client';
import { useUnit } from 'effector-react';
import { navigationTriggered } from '@/your-path-name';
...
export function goToSomeRouteNameButton() {
const goToSomeRouteName = useUnit(navigationTriggered);
return (
);
}
```
--------------------------------
### Subscribing to Store Updates with sample
Source: https://effector.dev/en/llms-full.txt
Shows how to use `sample` to trigger logic when a store's updates event fires. This allows reacting to store changes.
```ts
// this code is equivalent to the example on the right
import { createStore, sample } from "effector";
const $someStore = createStore();
sample({
clock: $someStore,
// ...
});
```
```ts
// this code is equivalent to the example on the left
import { createStore, sample } from "effector";
const $someStore = createStore();
sample({
clock: $someStore.updates,
// ...
});
```
--------------------------------
### Modify Model with useEditKeyval Hook
Source: https://effector.dev/en/llms-full.txt
Demonstrates using the `useEditKeyval` hook from `effector-react` to get methods for modifying a `keyval` model. The example shows destructuring `add`, `map`, `remove`, `replaceAll`, `set`, and `update` functions.
```typescript
const { add, map, remove, replaceAll, set, update } = useEditKeyval(ordersList);
```
--------------------------------
### sample(source, clock, fn?)
Source: https://effector.dev/en/llms-full.txt
This is a shorthand version of the `sample` method, which always implicitly returns a `target`. It supports multiple patterns for providing arguments: all arguments (source, clock, fn), just source and clock, source and fn (where source acts as the trigger), or only source (which acts as both trigger and source).
```APIDOC
## sample(source, clock, fn?)
### Description
This method samples data from a `source` unit when a `clock` unit is triggered. An optional transformation function `fn` can be provided to process the data before it is sent to an implicit target. The method supports various argument combinations for flexibility.
### Method Signature
```ts
sample(source, clock, fn?): Unit
```
### Parameters
#### `source`
- **Type**: `Unit | Unit[]`
- **Description**: Acts as the data source when the `clock` triggers. If no `clock` is provided, `source` is used as the trigger. Can be a `Store`, `Event`, `Effect`, or an array of units.
#### `clock`
- **Type**: `Unit | Unit[]`
- **Description**: Optional. The unit that acts as the trigger to read from `source`. Can be an `Event`, `Store`, `Effect`, or an array of units.
#### `fn`
- **Type**: `(source: Source, clock: Clock) => result`
- **Description**: Optional. A transformation function to be applied before sending the result to the implicit target. The function must be pure.
### Examples
#### Example 1: With clock and transformation function
```ts
const $userName = createStore("john");
const submitForm = createEvent();
const sampleUnit = sample(
$userName, // Source
submitForm, // Clock
(name, password) => ({ name, password }) // fn
);
submitForm(12345678);
// 1. submitForm is triggered with 12345678
// 2. $userName value is read ("john")
// 3. The values are transformed and passed to sampleUnit
```
#### Example 2: With clock only
```ts
const clicked = createEvent();
const $store = createStore(0);
const fetchFx = createEffect();
sample($data, clicked);
sample($data, $store);
```
#### Example 3: With source only (source acts as clock)
```ts
// Assuming $data is a Store or Event
sample($data);
```
### Return Value
The return type depends on the combination of units used and the return type of `fn`, if present. Otherwise, it falls back to the `source`.
```
--------------------------------
### Example of legacy fork() usage with a domain
Source: https://effector.dev/en/llms-full.txt
Shows how to create a scope using the legacy `fork(domain, options)` signature, initializing a store within that domain's scope.
```typescript
import { createDomain, createStore, fork } from "effector";
const app = createDomain();
const $flag = app.createStore(false);
const scope = fork(app, {
values: [[$flag, true]],
});
console.log(scope.getState($flag)); // => true
```
--------------------------------
### Basic useGate Example
Source: https://effector.dev/en/llms-full.txt
Demonstrates how to use the useGate hook to pass props to a Gate. This is useful for initializing or updating gate state based on component props.
```javascript
import { createGate, useGate } from "effector-react";
import { Route } from "react-router";
const PageGate = createGate("page");
PageGate.state.watch(({ match }) => {
console.log(match);
});
const Home = (props) => {
useGate(PageGate, props);
return Home;
};
const App = () => ;
```
--------------------------------
### Basic createGate Usage
Source: https://effector.dev/en/llms-full.txt
Demonstrates how to create and use a Gate with props in a SolidJS application. It shows how to watch the gate's state and how it changes upon mounting and unmounting.
```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 {}
```
--------------------------------
### Create Redux Integration with setup event
Source: https://withease.effector.dev/redux
Initialize Redux integration with a Redux store and a setup event. The setup event is required to initialize the interoperability, typically an application lifecycle event.
```typescript
const myReduxStore = configureStore({
// ...
});
const reduxInterop = createReduxIntegration({
reduxStore: myReduxStore,
setup: appStarted,
});
```
--------------------------------
### Initialize with Static i18next Instance
Source: https://withease.effector.dev/i18next
Set up the i18next integration by passing a static i18next instance. The integration is activated when the `appStarted` event is dispatched.
```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
```
--------------------------------
### Install Effector Model Package
Source: https://effector.dev/en/llms-full.txt
Command to install the Effector model package using npm.
```bash
npm install @effector/model
```
--------------------------------
### Local Factory Definition Example
Source: https://effector.dev/en/llms-full.txt
An example TypeScript file defining a custom factory function 'createBooleanStore'.
```typescript
import { createStore } from "effector";
/* createBooleanStore is a factory */
export const createBooleanStore = () => createStore(true);
```
--------------------------------
### Sample with Source, Clock, and Transformation Function
Source: https://effector.dev/en/llms-full.txt
Demonstrates using sample with a source store, a clock event, and a transformation function to combine data.
```typescript
const $userName = createStore("john");
const submitForm = createEvent();
const sampleUnit = sample(
$userName /* 2 */,
submitForm /* 1 */,
(name, password) => ({ name, password }) /* 3 */
);
submitForm(12345678);
// 1. submitForm is triggered with 12345678
// 2. $userName value is read ("john")
// 3. The values are transformed and passed to sampleUnit
```
--------------------------------
### Install Effector with yarn
Source: https://effector.dev/en/llms-full.txt
Install the Effector library using yarn. This command is an alternative to npm for package management.
```bash
yarn install effector
```
--------------------------------
### Install Effector SWC Plugin with pnpm
Source: https://effector.dev/en/llms-full.txt
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://effector.dev/en/llms-full.txt
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://effector.dev/en/llms-full.txt
Install the Effector SWC plugin as a development dependency using npm.
```bash
npm install --save-dev @effector/swc-plugin
```
--------------------------------
### sample
Source: https://effector.dev/en/llms-full.txt
The `sample` unit triggers a target based on a clock and/or source. It allows for optional filtering, data transformation, and batching of updates.
```APIDOC
## sample
### Description
The `sample` unit allows you to trigger a target unit based on a clock and/or source, with optional filtering, transformation, and batching.
### Method
N/A (This is a unit/function call, not an HTTP endpoint)
### Endpoint
N/A
### Parameters
#### `clock`
A trigger unit that determines when to sample the source. Optional.
* **Type**: `Unit | Unit[]`
* **Can be**: `Event`, `Store`, `Effect`, `Unit[]`
> INFO: Either `clock` or `source` is required.
#### `source`
The data source to be read when the `clock` unit triggers. If `clock` is not provided, then `source` is used as the `clock`. Optional.
* **Type**: `Unit | Unit[] | { [key: string]: Unit }`
* **Can be**: `Store`, `Event`, `Effect`, Object of units, Array of units
> INFO: Either `source` or `clock` is required.
#### `filter`
A predicate function or store used to filter the data. If it returns `false`, the data will not be passed to `target`. Optional.
* **Type**: `Store | (source: Source, clock: Clock) => (boolean | Store)`
* **Can be**: `Store`, Predicate function
#### `fn`
A function used to transform the data before passing it to the `target`. The function must be pure. Optional.
* **Type**: `(source: Source, clock: Clock) => Target`
> INFO: The type of data returned must match the type of data in `target`.
#### `target`
The destination unit that will receive the data and be triggered. Optional.
* **Type**: `Unit | Unit[]`
* **Can be**: `EventCallable`, `Effect`, `StoreWritable`, `Unit[]`
> INFO: If `target` is not specified, `sample` returns a new derived unit.
#### `batch`
Enables batching of updates for better performance. Default is `true`. Optional.
* **Type**: `boolean` (Default: `true`)
#### `name`
The `name` field allows you to assign a debug-friendly name to the created unit. Optional.
* **Type**: `string`
### Request Example
```ts
// Example with clock and source
sample({
source: $data,
clock: clicked,
});
// Example with filter and fn
sample({
clock: checkScore,
source: $score,
filter: (score) => score > 100,
fn: (score) => score * 2,
target: showWinnerFx,
});
// Example with target as an event
sample({
source: $store,
clock: trigger,
target: targetEvent,
});
```
### Response
N/A (This unit returns a new derived unit if `target` is not specified, otherwise it triggers the target.)
### Error Handling
N/A
```
--------------------------------
### Install Effector Vue Plugin
Source: https://effector.dev/en/llms-full.txt
Installs the VueEffector plugin for Vue 3 applications. This enables effector-vue integration.
```javascript
import { createApp } from "vue";
import { VueEffector } from "effector-vue/options-vue3";
import App from "./App.vue";
const app = createApp(App);
app.use(VueEffector);
```
--------------------------------
### Install Effector for React
Source: https://effector.dev/en/llms-full.txt
Install the effector and effector-react packages for React integration. This is the primary way to use Effector with React applications.
```bash
npm install effector effector-react
```
--------------------------------
### Using Custom Factory
Source: https://effector.dev/en/llms-full.txt
Demonstrates importing and using the `createName` custom factory to create multiple instances.
```typescript
// src/feature/persons/model.ts
import { createName } from "@/shared/lib/create-name";
const personOne = createName();
const personTwo = createName();
```
--------------------------------
### Install Effector Model React Integration Package
Source: https://effector.dev/en/llms-full.txt
Command to install the Effector model React integration package using npm.
```bash
npm install @effector/model-react
```
--------------------------------
### Install Effector for Vue
Source: https://effector.dev/en/llms-full.txt
Install the effector and effector-vue packages for Vue integration. This enables Effector's reactive capabilities within Vue components.
```bash
npm install effector effector-vue
```
--------------------------------
### restore(event, defaultState)
Source: https://effector.dev/en/llms-full.txt
Creates a new store from an event. It initializes the store with `defaultState` and updates it with the payload of the given event. This is a shortcut for `createStore(defaultState).on(event, (_, payload) => payload)`.
```APIDOC
## restore(event, defaultState)
### Description
Creates a new store initialized with `defaultState` and updated by the provided `event`.
### Method Signature
```ts
restore(event: Event, defaultState: T): StoreWritable
```
### Arguments
* `event` - The event that will trigger store updates.
* `defaultState` (*Payload*) - The initial value of the store.
### Returns
* A new writable store (`StoreWritable`).
### Examples
#### Basic Usage
```js
import { createEvent, restore } from "effector";
const event = createEvent();
const $store = restore(event, "default");
$store.watch((state) => console.log("state: ", state));
// state: default
event("foo");
// state: foo
```
```
--------------------------------
### Creating a Store with Initial Value
Source: https://effector.dev/en/llms-full.txt
Demonstrates the creation of a store with a specified initial value.
```typescript
import { createStore } from "effector";
// creating a store with an initial value
const $counter = createStore(0);
```
--------------------------------
### Babel Configuration for Custom Unit Factories with `noDefaults`
Source: https://effector.dev/en/llms-full.txt
Example Babel configuration demonstrating how to use `effector/babel-plugin` with `addLoc`, `importName`, `storeCreators`, and `noDefaults` for custom unit factories.
```json
{
"plugins": [
["effector/babel-plugin", { "addLoc": true }],
[
"effector/babel-plugin",
{
"importName": "@lib/createInputField",
"storeCreators": ["createInputField"],
"noDefaults": true
},
"createInputField"
]
]
}
```
--------------------------------
### Example: Setting initial state and replacing an effect handler
Source: https://effector.dev/en/llms-full.txt
Illustrates creating a scope with a specific user ('alice') and overriding the `fetchFriendsFx` to return predefined data. Shows how the overridden handler affects the scope's state.
```typescript
import { createEffect, createStore, fork, allSettled } from "effector";
const fetchFriendsFx = createEffect<{ limit: number }, string[]>(async ({ limit }) => {
return [];
});
const $user = createStore("guest");
const $friends = createStore([]);
$friends.on(fetchFriendsFx.doneData, (_, result) => result);
const testScope = fork({
values: [[$user, "alice"]],
handlers: [[fetchFriendsFx, () => ["bob", "carol"]]],
});
await allSettled(fetchFriendsFx, {
scope: testScope,
params: { limit: 10 },
});
console.log(testScope.getState($friends));
// => ['bob', 'carol']
```
--------------------------------
### Sample with Source Parameter
Source: https://effector.dev/en/llms-full.txt
Illustrates using the 'source' parameter. If 'clock' is omitted, 'source' acts as the clock.
```typescript
sample({
source: $data,
clock: clicked,
});
sample({
source: $data,
clock: $store,
});
sample({
source: $data,
clock: [clicked, fetchFx.done],
});
```
--------------------------------
### Declarative Event Triggering with sample
Source: https://effector.dev/en/llms-full.txt
This snippet demonstrates a declarative approach using `sample` to trigger an event when a store's value changes. This is the preferred method for managing reactive updates.
```javascript
import { createStore, createEvent, sample } from "effector";
const submitLoginSize = createEvent();
const $login = createStore("guest");
const $loginSize = $login.map((login) => login.length);
sample({
clock: $loginSize,
target: submitLoginSize,
});
```
--------------------------------
### Working with Stores using merge
Source: https://effector.dev/en/llms-full.txt
Shows how to merge two stores (`$foo` and `$bar`) using the `merge` function. The `anyUpdated` event logs the new state whenever either `$foo` or `$bar` is updated.
```javascript
import { createEvent, createStore, merge } from "effector";
const setFoo = createEvent();
const setBar = createEvent();
const $foo = createStore(0).on(setFoo, (_, v) => v);
const $bar = createStore(100).on(setBar, (_, v) => v);
const anyUpdated = merge([$foo, $bar]);
anyUpdated.watch((v) => console.log(`state changed to: ${v}`));
setFoo(1); // => state changed to: 1
setBar(123); // => state changed to: 123
```
--------------------------------
### Derived store creation with `sample`
Source: https://effector.dev/en/llms-full.txt
Use `sample` to create a derived store when both `clock` and `source` are stores. The derived store updates when the `clock` store updates, using the value from the `source` store at that moment.
```typescript
const $derivedStore = sample({
clock: $store,
source: $secondStore,
});
// Returns a derived store because both clock and source are stores
```
--------------------------------
### Restore store from event
Source: https://effector.dev/en/llms-full.txt
Creates a new store initialized with a default state and updated by a specific event. This is a shortcut for creating a store and handling the event.
```javascript
import { createEvent, restore } from "effector";
const event = createEvent();
const $store = restore(event, "default");
$store.watch((state) => console.log("state: ", state));
// state: default
event("foo");
// state: foo
```
--------------------------------
### Example: Watching Effect Calls
Source: https://effector.dev/en/llms-full.txt
Shows how to use the `.watch()` method to log the arguments passed to an effect whenever it's called. The returned subscription can be used to stop watching.
```javascript
import { createEffect } from "effector";
const fx = createEffect((params) => params);
fx.watch((params) => {
console.log("effect called with argument", params);
});
await fx(10);
// => effect called with argument 10
```
--------------------------------
### User Display Component
Source: https://effector.dev/en/llms-full.txt
A simple Vue component to display user information, intended to be used with the useStoreMap example.
```jsx
[{user.id}] {user.name}
```
--------------------------------
### Create an Effect
Source: https://effector.dev/en/llms-full.txt
Imports and creates a basic effect instance. This is the starting point for defining side effect handlers.
```typescript
import { type Effect, createEffect } from "effector";
const effectFx = createEffect();
```