### Install Flurx using npm
Source: https://github.com/qwtel/flurx/blob/master/README.md
This command installs the Flurx library, which is a Flux implementation using RxJS. It is a necessary step before using Flurx in your project.
```bash
npm install flurx
```
--------------------------------
### Flurx React Example: Login Flow
Source: https://github.com/qwtel/flurx/blob/master/README.md
Demonstrates a typical Flurx implementation in a React application. It includes defining Actions for login events, creating a LoginStore to manage authentication state, and a LoginComponent to interact with the store and dispatch actions. The example showcases state subscription and updates.
```javascript
import React from 'react';
import {Store, Action} from 'flurx';
const LoginAction = Action.create();
const LoginActionSuccess = Action.create();
const LoginActionFailure = Action.create();
class LoginStore extends Store {
constructor() {
super({
isLoggedIn: false,
username: null,
warn: null
});
this.register(LoginAction, this.onLogin);
this.register(LoginActionSuccess, this.onLoginSuccess);
this.register(LoginActionFailure, this.onLoginFailure);
}
onLogin(store, username, password) {
if (!store.isLoggedIn) {
getJSON('/login', {username, password})
.then(LoginActionSuccess)
.catch(LoginActionFailure);
return Object.assign(store, {
isLoggedIn: true,
username,
warn: null
});
}
return store;
}
onLoginSuccess(store, result) {
return Object.assign(store, {
isLoggedIn: true,
username: result.username,
warn: null
});
}
onLoginFailure(store, err) {
return Object.assign(store, {
isLoggedIn: false,
username: null,
warn: err.message
})
}
}
const loginStore = new LoginStore();
const LoginComponent = React.createClass({
getInitialState() {
return loginStore.getValue();
},
componentDidMount() {
loginStore.subscribe(store => {
this.setState(store);
});
},
onSubmit(e) {
e.preventDefault();
const username = this.refs.username.getValue().trim();
const password = this.refs.password.getValue().trim();
if (!username || !password) {
return;
}
LoginAction(username, password);
},
render() {
return (
!this.state.isLoggedIn ?
:
Welcome, {this.state.username}.
);
}
});
```
--------------------------------
### Flurx React Integration for Login Flow
Source: https://context7.com/qwtel/flurx/llms.txt
A comprehensive example showcasing Flurx integration with React for a login feature. It includes asynchronous operations, multiple stores, and handles login success and failure states. The component subscribes to the AuthStore and manages its local state based on store updates.
```javascript
import React from 'react';
import { Store, Action } from 'flurx';
// Actions
const LoginAction = Action.create();
const LoginSuccessAction = Action.create();
const LoginFailureAction = Action.create();
const LogoutAction = Action.create();
// Auth Store
class AuthStore extends Store {
constructor() {
super({
isLoggedIn: false,
isLoading: false,
user: null,
error: null
});
this.register(LoginAction, this.onLogin);
this.register(LoginSuccessAction, this.onLoginSuccess);
this.register(LoginFailureAction, this.onLoginFailure);
this.register(LogoutAction, this.onLogout);
}
onLogin(state, username, password) {
// Simulate async login
fetch('/api/login', {
method: 'POST',
body: JSON.stringify({ username, password })
})
.then(res => res.json())
.then(user => LoginSuccessAction(user))
.catch(err => LoginFailureAction(err.message));
return {
...state,
isLoading: true,
error: null
};
}
onLoginSuccess(state, user) {
return {
isLoggedIn: true,
isLoading: false,
user,
error: null
};
}
onLoginFailure(state, errorMessage) {
return {
isLoggedIn: false,
isLoading: false,
user: null,
error: errorMessage
};
}
onLogout(state) {
return {
isLoggedIn: false,
isLoading: false,
user: null,
error: null
};
}
}
const authStore = new AuthStore();
// React Component
const LoginComponent = React.createClass({
getInitialState() {
return authStore.getValue();
},
componentDidMount() {
this.subscription = authStore.subscribe(state => {
this.setState(state);
});
},
componentWillUnmount() {
this.subscription.dispose();
},
handleSubmit(e) {
e.preventDefault();
const username = this.refs.username.value.trim();
const password = this.refs.password.value.trim();
if (username && password) {
LoginAction(username, password);
}
},
handleLogout() {
LogoutAction();
},
render() {
const { isLoggedIn, isLoading, user, error } = this.state;
if (isLoggedIn) {
return (
Welcome, {user.name}!
);
}
return (
);
}
});
```
--------------------------------
### Create Flurx Store with Initial State
Source: https://context7.com/qwtel/flurx/llms.txt
Demonstrates how to create a new Store instance with an initial state. Stores extend BehaviorSubject, ensuring subscribers receive the current value immediately. The initial state can be a complex object representing domain data.
```javascript
import { Store, Action } from 'flurx';
// Create a store with initial state
class UserStore extends Store {
constructor() {
super({
currentUser: null,
isAuthenticated: false,
preferences: {
theme: 'light',
notifications: true
}
});
}
}
const userStore = new UserStore();
// Subscribers immediately receive the initial state
userStore.subscribe(state => {
console.log('User state:', state);
// Output: User state: { currentUser: null, isAuthenticated: false, preferences: { theme: 'light', notifications: true } }
});
// Create a store with simple initial value
class CounterStore extends Store {
constructor() {
super({ count: 0 });
}
}
const counterStore = new CounterStore();
console.log('Initial count:', counterStore.getValue().count);
// Output: Initial count: 0
```
--------------------------------
### Create and Use Actions in Flurx
Source: https://context7.com/qwtel/flurx/llms.txt
Demonstrates how to create Actions using `Action.create()`. Actions are observable subjects that dispatch events. This snippet shows how to subscribe to actions, call them with parameters, and handle different event types like login and item addition.
```javascript
import { Action } from 'flurx';
// Create actions for a login flow
const LoginAction = Action.create();
const LoginSuccessAction = Action.create();
const LoginFailureAction = Action.create();
// Subscribe directly to an action to observe when it's called
LoginAction.subscribe(params => {
console.log('Login attempted with:', params[0], params[1]);
// Output: Login attempted with: john@example.com secretpassword
});
// Call the action with parameters (like calling a function)
LoginAction('john@example.com', 'secretpassword');
// Actions can be called with any number of arguments
const AddItemAction = Action.create();
AddItemAction({ id: 1, name: 'Product', price: 29.99 });
const UpdateQuantityAction = Action.create();
UpdateQuantityAction(1, 5); // itemId, newQuantity
```
--------------------------------
### Action.create()
Source: https://context7.com/qwtel/flurx/llms.txt
Creates a new Action that functions as an RxJS Subject, allowing for event dispatching and observation.
```APIDOC
## Action.create()
### Description
Creates a new Action that can be called like a function and observed like an RxJS Subject. Actions serve as the mechanism for dispatching events throughout the application.
### Method
N/A (Function Call)
### Parameters
- **...args** (any) - Optional - Any number of arguments to pass to subscribers.
### Request Example
```javascript
const LoginAction = Action.create();
LoginAction('user@example.com', 'password');
```
### Response
- **Action** (Function) - A callable function that acts as an RxJS Subject.
```
--------------------------------
### Synchronize Store Updates with Action.waitFor()
Source: https://context7.com/qwtel/flurx/llms.txt
Illustrates using `Action.waitFor()` to ensure that multiple Stores have completed processing an Action before a subsequent operation occurs. This is crucial for maintaining state consistency when updates depend on each other. It defines two Stores, `InventoryStore` and `OrderStore`, and uses `SaveOrderAction` to trigger updates in both, waiting for both to finish before logging the results.
```javascript
import { Action, Store } from 'flurx';
const SaveOrderAction = Action.create();
// Create stores for different parts of application state
class InventoryStore extends Store {
constructor() {
super({ items: { 1: { stock: 100 }, 2: { stock: 50 } } });
this.register(SaveOrderAction, this.onSaveOrder);
}
onSaveOrder(state, orderId, itemId, quantity) {
const newStock = state.items[itemId].stock - quantity;
return {
...state,
items: {
...state.items,
[itemId]: { stock: newStock }
}
};
}
}
class OrderStore extends Store {
constructor() {
super({ orders: [] });
this.register(SaveOrderAction, this.onSaveOrder);
}
onSaveOrder(state, orderId, itemId, quantity) {
return {
...state,
orders: [...state.orders, { orderId, itemId, quantity }]
};
}
}
const inventoryStore = new InventoryStore();
const orderStore = new OrderStore();
// Wait for both stores to process the action before logging
SaveOrderAction.waitFor([inventoryStore, orderStore]).subscribe(params => {
const [orderId, itemId, quantity] = params;
console.log(`Order ${orderId} completed: ${quantity} of item ${itemId}`);
console.log('Inventory updated:', inventoryStore.getValue());
console.log('Orders updated:', orderStore.getValue());
});
// Dispatch the action
SaveOrderAction('ORD-001', 1, 10);
// Output:
// Order ORD-001 completed: 10 of item 1
// Inventory updated: { items: { 1: { stock: 90 }, 2: { stock: 50 } } }
// Orders updated: { orders: [{ orderId: 'ORD-001', itemId: 1, quantity: 10 }] }
```
--------------------------------
### Action.waitFor()
Source: https://context7.com/qwtel/flurx/llms.txt
Synchronizes state updates by waiting for multiple Stores to process an Action before executing a callback.
```APIDOC
## Action.waitFor()
### Description
Allows waiting for multiple Stores to complete their updates before proceeding. This ensures proper synchronization of state updates across the application.
### Method
N/A (Method)
### Parameters
- **stores** (Array) - Required - An array of Store instances to wait for.
### Request Example
```javascript
SaveOrderAction.waitFor([inventoryStore, orderStore]).subscribe(params => {
console.log('All stores updated');
});
```
### Response
- **Observable** (RxJS Observable) - An observable that emits once all registered stores have processed the action.
```
--------------------------------
### Flurx Store Subscription and Actions
Source: https://context7.com/qwtel/flurx/llms.txt
Demonstrates subscribing to state changes in a Flurx Store and dispatching actions to modify the state. The Store extends BehaviorSubject, ensuring immediate invocation of the callback with the current state upon subscription. Returns a subscription object that can be disposed to stop updates.
```javascript
import { Store, Action } from 'flurx';
const AddTodoAction = Action.create();
const ToggleTodoAction = Action.create();
const RemoveTodoAction = Action.create();
class TodoStore extends Store {
constructor() {
super({ todos: [], filter: 'all' });
this.register(AddTodoAction, this.onAddTodo);
this.register(ToggleTodoAction, this.onToggleTodo);
this.register(RemoveTodoAction, this.onRemoveTodo);
}
onAddTodo(state, text) {
const newTodo = {
id: Date.now(),
text,
completed: false
};
return {
...state,
todos: [...state.todos, newTodo]
};
}
onToggleTodo(state, id) {
return {
...state,
todos: state.todos.map(todo =>
todo.id === id ? { ...todo, completed: !todo.completed } : todo
)
};
}
onRemoveTodo(state, id) {
return {
...state,
todos: state.todos.filter(todo => todo.id !== id)
};
}
}
const todoStore = new TodoStore();
// Subscribe to state changes
const subscription = todoStore.subscribe(state => {
console.log('Todos:', state.todos.length);
state.todos.forEach(todo => {
console.log(` [${todo.completed ? 'x' : ' '}] ${todo.text}`);
});
});
// Dispatch actions
AddTodoAction('Learn Flurx');
// Output: Todos: 1
// [ ] Learn Flurx
AddTodoAction('Build an app');
// Output: Todos: 2
// [ ] Learn Flurx
// [ ] Build an app
ToggleTodoAction(todoStore.getValue().todos[0].id);
// Output: Todos: 2
// [x] Learn Flurx
// [ ] Build an app
// Unsubscribe when done (e.g., component unmount)
subscription.dispose();
```
--------------------------------
### Register Action Handlers in Flurx Store
Source: https://context7.com/qwtel/flurx/llms.txt
Shows how to register handler functions for specific Actions within a Store. Handlers receive the current state and action parameters, returning the new state. This allows for predictable state mutations in response to dispatched actions.
```javascript
import { Store, Action } from 'flurx';
// Define actions
const IncrementAction = Action.create();
const DecrementAction = Action.create();
const SetValueAction = Action.create();
const ResetAction = Action.create();
class CounterStore extends Store {
constructor() {
super({ count: 0, lastAction: null });
// Register handlers for each action
this.register(IncrementAction, this.onIncrement);
this.register(DecrementAction, this.onDecrement);
this.register(SetValueAction, this.onSetValue);
this.register(ResetAction, this.onReset);
}
onIncrement(state, amount = 1) {
return {
count: state.count + amount,
lastAction: 'increment'
};
}
onDecrement(state, amount = 1) {
return {
count: state.count - amount,
lastAction: 'decrement'
};
}
onSetValue(state, newValue) {
return {
count: newValue,
lastAction: 'set'
};
}
onReset(state) {
return { count: 0, lastAction: 'reset' };
}
}
const counterStore = new CounterStore();
// Subscribe to state changes
counterStore.subscribe(state => {
console.log(`Count: ${state.count}, Last action: ${state.lastAction}`);
});
// Dispatch actions
IncrementAction(); // Output: Count: 1, Last action: increment
IncrementAction(5); // Output: Count: 6, Last action: increment
DecrementAction(2); // Output: Count: 4, Last action: decrement
SetValueAction(100); // Output: Count: 100, Last action: set
ResetAction(); // Output: Count: 0, Last action: reset
```
--------------------------------
### Retrieve Current State Value from Flurx Store
Source: https://context7.com/qwtel/flurx/llms.txt
Explains how to synchronously retrieve the current state value of a Store using `getValue()`. This method is inherited from RxJS BehaviorSubject and is useful for accessing the state without subscribing, such as for initializing component state in frameworks like React.
```javascript
import { Store, Action } from 'flurx';
const UpdateProfileAction = Action.create();
class ProfileStore extends Store {
constructor() {
super({
name: 'Guest',
email: null,
avatar: '/default-avatar.png'
});
this.register(UpdateProfileAction, this.onUpdateProfile);
}
onUpdateProfile(state, updates) {
return { ...state, ...updates };
}
}
const profileStore = new ProfileStore();
// Get current value synchronously
const currentProfile = profileStore.getValue();
console.log('Current profile:', currentProfile);
// Output: Current profile: { name: 'Guest', email: null, avatar: '/default-avatar.png' }
// Update the profile
UpdateProfileAction({ name: 'John Doe', email: 'john@example.com' });
// Get the updated value
console.log('Updated profile:', profileStore.getValue());
// Output: Updated profile: { name: 'John Doe', email: 'john@example.com', avatar: '/default-avatar.png' }
// Useful for React component initialization
const MyComponent = React.createClass({
getInitialState() {
// Synchronously get current store value for initial component state
return profileStore.getValue();
},
componentDidMount() {
// Subscribe to future updates
this.subscription = profileStore.subscribe(state => {
this.setState(state);
});
},
componentWillUnmount() {
this.subscription.dispose();
},
render() {
return
Hello, {this.state.name}!
;
}
});
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.