### Install Statux using npm
Source: https://github.com/franciscop/statux/blob/master/README.md
This command installs the Statux library. It is a prerequisite for using Statux in your React project.
```bash
npm install statux
```
--------------------------------
### Initial Data Loading from API with Statux
Source: https://github.com/franciscop/statux/blob/master/README.md
This example illustrates how to fetch initial data from an API and populate the Statux store. It demonstrates using `useEffect` to perform the API call upon component mount and updating the store with the fetched data. The component displays a loading message until the data is available.
```javascript
// src/App.js
import Store from "statux";
import PokemonList from "./PokemonList";
export default () => (
The Best 151:
);
```
```javascript
// src/PokemonList.js
import { useStore } from "statux";
import { useEffect } from "react";
import styled from "styled-components";
const url = "https://pokeapi.co/api/v2/pokemon/?limit=151";
const catchAll = () =>
fetch(url)
.then((r) => r.json())
.then((r) => r.results);
const Pokemon = styled.div`...`;
const Label = styled.div`...`;
export default () => {
const [pokemon, setPokemon] = useStore("pokemon");
useEffect(() => {
catchAll().then(setPokemon);
}, [setPokemon]);
if (!pokemon.length) return "Loading...";
return pokemon.map((poke, i) => (
));
};
```
--------------------------------
### Object State Modification with useActions Helpers
Source: https://github.com/franciscop/statux/blob/master/README.md
This example demonstrates how to use the helper methods of useActions for modifying object state. It covers methods like assign, extend, and remove, which are analogous to JavaScript's Object prototype methods.
```javascript
// For the state of: user = { id: 1, name: 'John' }
const setUser = useActions("user");setUser((user) => ({ ...user, name: "Sarah" })); // { id: 1, name: 'Sarah' }
setUser.assign({ name: "Sarah" }); // { id: 1, name: 'Sarah' }setUser.extend({ name: "Sarah" }); // { id: 1, name: 'Sarah' }
setUser.remove("name"); // { id: 1 }
```
--------------------------------
### Persisting Statux State with LocalStorage
Source: https://github.com/franciscop/statux/blob/master/README.md
This example demonstrates how to persist parts of the Statux state in the browser's `localStorage`. It shows how to read initial state from `localStorage` and how to set up a component that automatically saves state changes back to `localStorage`. This is useful for maintaining state across page reloads.
```javascript
import Store, { useSelector } from "statux";
// Define the initial state as an object:
const todo = JSON.parse(localStorage.todo || "[]");
// Listen for changes on the state and save it in localStorage:
const LocalStorage = () => {
const todo = useSelector("todo");
localStorage.todo = JSON.stringify(todo);
return null;
};
export default () => (
...
);
```
```javascript
import Store, { useSelector } from "statux";
// Define the initial state as an object:
const dark = localStorage.dark === "true";
// Save this state fragment when it changes:
const LocalStorage = () => {
localStorage.dark = useSelector("dark");
return null;
};
export default () => (
...
);
```
--------------------------------
### Modifying State with Spread Syntax and Callback (Statux)
Source: https://github.com/franciscop/statux/blob/master/README.md
Provides examples of updating state in Statux using the spread syntax, both directly and with a callback function. This is useful for updating objects and arrays immutably.
```javascript
// Set the name of the user
const onClick = (name) => setUser({ ...user, name });
const onClick = (name) => setUser((user) => ({ ...user, name }));
```
--------------------------------
### LocalStorage Persistence with Statux
Source: https://context7.com/franciscop/statux/llms.txt
This snippet demonstrates how to synchronize application state with the browser's LocalStorage using the statux library. It supports both manual synchronization via useEffect hooks and automatic synchronization using a '$' prefix for state keys. It also includes examples for a dark mode toggle persistence.
```javascript
import Store, { useSelector, useStore } from "statux";
import { useEffect } from "react";
// Manual localStorage sync component
function LocalStorageSync() {
const todos = useSelector("todos");
const settings = useSelector("settings");
useEffect(() => {
localStorage.setItem("todos", JSON.stringify(todos));
}, [todos]);
useEffect(() => {
localStorage.setItem("settings", JSON.stringify(settings));
}, [settings]);
return null; // This component only handles side effects
}
// Initialize from localStorage
const savedTodos = JSON.parse(localStorage.getItem("todos") || "[]");
const savedSettings = JSON.parse(
localStorage.getItem("settings") || '{"theme":"light","notifications":true}'
);
// App with manual localStorage
function ManualPersistenceApp() {
return (
);
}
// Automatic persistence using $ prefix
function AutoPersistenceApp() {
return (
);
}
// Dark mode with localStorage
const initialDarkMode = localStorage.getItem("darkMode") === "true";
function DarkModeToggle() {
const [darkMode, setDarkMode] = useStore("darkMode");
useEffect(() => {
localStorage.setItem("darkMode", darkMode);
document.body.classList.toggle("dark-mode", darkMode);
}, [darkMode]);
return (
);
}
function DarkModeApp() {
return (
);
}
export { ManualPersistenceApp, AutoPersistenceApp, DarkModeApp };
```
--------------------------------
### Advanced Array Helpers with useActions Hook (JavaScript)
Source: https://context7.com/franciscop/statux/llms.txt
Showcases advanced array manipulation using the .append(), .prepend(), and .remove(index) methods from the useActions hook. These enable adding elements to the end or start and removing elements by their index immutably.
```javascript
// Array helpers - append, prepend, remove by index
function BookManager() {
const setBooks = useActions("books");
const addBook = (book) => setBooks.append(book);
const addAtStart = (book) => setBooks.prepend(book);
const removeByIndex = (index) => setBooks.remove(index);
const handleSubmit = (formData) => {
addBook({
id: Date.now(),
title: formData.title,
author: formData.author,
year: formData.year
});
};
return (
);
}
```
--------------------------------
### Resetting Statux Initial State
Source: https://github.com/franciscop/statux/blob/master/README.md
This snippet illustrates how to reset the application's state back to its initial values using Statux. It shows defining an initial state object and then using the `useActions` hook without a selector to get a function that can set the entire state, effectively resetting it.
```javascript
import Store, { useActions, useStore } from "statux";
// Define the initial state as an object
const init = { user: null, todo: [] };
// We then trigger a useActions without any selector
const ResetState = () => {
const setState = useActions();
const reset = () => setState(init);
return ;
};
const Login = () => {
const [user, setUser] = useStore("user");
const login = () => setUser("Mike");
if (user) return
Hi {user}
;
return (
);
};
export default () => (
);
```
--------------------------------
### Direct State Manipulation in UserProfile Component (Statux)
Source: https://github.com/franciscop/statux/blob/master/README.md
An example of a React component using Statux's useStore to manage and update user state directly. This illustrates how Statux removes the need for separate actions and reducers common in Flux patterns.
```javascript
export default function UserProfile() {
const [user, setUser] = useStore("user");
if (!user) {
const login = () => setUser("Mike");
return ;
}
return user;
}
```
--------------------------------
### Using useActions in a React Component
Source: https://github.com/franciscop/statux/blob/master/README.md
This example demonstrates how to integrate the useActions hook within a React component, specifically for handling form submissions that update the application state. It shows the import statement and the component structure.
```javascript
import { useActions } from "statux";
import Form from "your-form-library";
const ChangeName = () => {
const setName = useActions("user.name");
const onSubmit = ({ name }) => setName(name);
return ;
};
```
--------------------------------
### Load Initial Data with Statux
Source: https://context7.com/franciscop/statux/llms.txt
This snippet demonstrates fetching a list of Pokemon data when the component mounts and the 'pokemon' state is empty. It uses `useEffect` to perform the asynchronous operation and `useStore` to update the global 'pokemon' state. This pattern is useful for initializing lists or other data required on application startup.
```javascript
// Load initial data on mount
function PokemonList() {
const [pokemon, setPokemon] = useStore("pokemon");
useEffect(() => {
const fetchPokemon = async () => {
const response = await fetch("https://pokeapi.co/api/v2/pokemon?limit=20");
const data = await response.json();
setPokemon(data.results);
};
if (pokemon.length === 0) {
fetchPokemon();
}
}, [pokemon.length, setPokemon]);
if (pokemon.length === 0) {
return
Loading Pokemon...
;
}
return (
{pokemon.map((p, i) => (
{p.name}
))}
);
}
```
--------------------------------
### Initialize Statux Store in App.js
Source: https://github.com/franciscop/statux/blob/master/README.md
This JavaScript code demonstrates how to initialize the Statux store by wrapping the main application component with the `` component. Initial state values are passed as props to ``.
```javascript
// src/App.js
import Store from "statux"; // This library
import Website from "./Website"; // Your code
// Initial state is { user: null, books: [] }
export default () => (
);
```
--------------------------------
### Complete App with Statux Store
Source: https://context7.com/franciscop/statux/llms.txt
This snippet sets up the main application component, wrapping child components within a Statux `Store` provider. It initializes the global state with 'user' set to null and 'pokemon' as an empty array. This ensures that the `UserProfile`, `PokemonList`, and `LoginForm` components can access and manipulate the shared state.
```javascript
// Complete app with async state
export default function App() {
return (
);
}
```
--------------------------------
### Initialize Statux Store with Initial State Object
Source: https://github.com/franciscop/statux/blob/master/README.md
This JavaScript code demonstrates initializing the Statux store with a pre-defined state object for better organization, especially as the state grows.
```javascript
// src/App.js
import Store from "statux";
import Navigation from "./Navigation";
const initialState = {
id: null,
friends: [],
// ...
};
export default () => (
);
```
--------------------------------
### TODO List Implementation with Statux
Source: https://github.com/franciscop/statux/blob/master/README.md
This snippet demonstrates a simple TODO list application built with Statux. It shows how to manage a list of items, add new items using a form, and toggle the completion status of individual items. It utilizes the `useStore` hook for state management and `form-mate` for form handling.
```javascript
// App.js
export default () => (
TODO List:
);
```
```javascript
// TodoList.js
import { useStore } from "statux";
import Form from "form-mate";
function TodoItem({ index }) {
const [item, setItem] = useStore(`todo.${index}`);
return (
);
}
```
--------------------------------
### Store Component - Initialize Global State
Source: https://context7.com/franciscop/statux/llms.txt
The `` component is used to wrap your application and define the initial global state structure. Properties prefixed with '$' are automatically persisted to localStorage.
```APIDOC
## Store Component - Initialize Global State
### Description
The `` component wraps your application and defines the initial global state structure through its props. All prop names become state keys, and their values become the initial state. State properties prefixed with `$` are automatically persisted to localStorage.
### Method
React Component
### Endpoint
N/A (Component)
### Parameters
#### Props
- **`*`** (any) - Required - Any valid React prop can be used to initialize state. Properties prefixed with `$` will be persisted to localStorage.
### Request Example
```javascript
import Store from "statux";
import App from "./App";
// Basic initialization
export default () => (
);
// With localStorage persistence ($ prefix)
export default () => (
);
// Using external state object
const initialState = {
user: null,
todos: [],
filters: { completed: false, active: true }
};
export default () => (
);
```
### Response
N/A (Component renders children)
```
--------------------------------
### Complete Todo App with Statux and React
Source: https://context7.com/franciscop/statux/llms.txt
This JavaScript code demonstrates a complete Todo list application using the Statux state management library with React. It includes components for individual todo items and the main todo list manager, along with functions for adding, toggling, and clearing todos. The application is initialized with an empty todo list.
```javascript
import Store, { useStore } from "statux";
import { useState } from "react";
// Individual todo item component
function TodoItem({ index }) {
const [todo, setTodo] = useStore(`todos.${index}`);
const toggleDone = () => {
setTodo.assign({ done: !todo.done });
};
const updateText = (newText) => {
setTodo.assign({ text: newText });
};
return (
);
}
// App with Store initialization
export default function App() {
return (
);
}
```
--------------------------------
### Initialize Global State with Statux Store Component
Source: https://context7.com/franciscop/statux/llms.txt
The component initializes the global state for the Statux library. It accepts props where prop names become state keys and their values become initial states. Properties prefixed with '$' are automatically persisted to localStorage.
```javascript
import Store from "statux";
import App from "./App";
// Basic initialization
export default () => (
);
// With localStorage persistence ($ prefix)
export default () => (
);
// Using external state object
const initialState = {
user: null,
todos: [],
filters: { completed: false, active: true }
};
export default () => (
);
```
--------------------------------
### State Reset and Management with Statux
Source: https://context7.com/franciscop/statux/llms.txt
This snippet illustrates various patterns for resetting and managing application state within statux. It covers resetting the entire state to its initial values, clearing specific parts of the state, and implementing logout functionality that also clears LocalStorage and reloads the application.
```javascript
import Store, { useActions, useStore, useSelector } from "statux";
// Define initial state separately for reuse
const initialState = {
user: null,
todos: [],
filters: { completed: false, search: "" },
settings: { theme: "light", language: "en" }
};
// Reset entire state
function ResetButton() {
const setState = useActions(); // No selector = root state
const handleReset = () => {
if (confirm("Reset all data?")) {
setState(initialState);
}
};
return ;
}
// Selective state clearing
function ClearDataButtons() {
const setTodos = useActions("todos");
const setUser = useActions("user");
const setFilters = useActions("filters");
const setState = useActions();
const clearTodos = () => setTodos([]);
const logout = () => setUser(null);
const resetFilters = () => setFilters({ completed: false, search: "" });
const factoryReset = () => setState(initialState);
return (
);
}
// Reset with confirmation and feedback
function AdvancedReset() {
const setState = useActions();
const user = useSelector("user");
const todoCount = useSelector((state) => state.todos.length);
const handleLogout = () => {
const confirmed = confirm(
`Logout ${user?.name}? This will clear ${todoCount} todos.`
);
if (confirmed) {
setState(initialState);
localStorage.clear(); // Also clear localStorage
window.location.reload(); // Optional: reload app
}
};
return user ? (
) : null;
}
// App with reset functionality
export default function App() {
return (
);
}
```
--------------------------------
### Fetch and Display User Data with Statux
Source: https://context7.com/franciscop/statux/llms.txt
This snippet demonstrates fetching user data from an external API, managing loading and error states, and updating the 'user' slice of the Statux store. It utilizes `useState` for local component state and `useStore` for global state management. The function handles success and error scenarios, displaying appropriate UI feedback.
```javascript
import Store, { useStore, useSelector, useActions } from "statux";
import { useEffect, useState } from "react";
// Fetch and display user data
function UserProfile() {
const [user, setUser] = useStore("user");
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const loadUser = async (userId) => {
setLoading(true);
setError(null);
try {
const response = await fetch(`https://api.example.com/users/${userId}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
setUser(data);
} catch (err) {
setError(err.message);
setUser(null);
} finally {
setLoading(false);
}
};
if (loading) return
Loading...
;
if (error) return
Error: {error}
;
if (!user) {
return ;
}
return (
{user.name}
{user.email}
);
}
```
--------------------------------
### Global State with useStore (Statux vs React Hooks)
Source: https://github.com/franciscop/statux/blob/master/README.md
Demonstrates the equivalent usage of Statux's useStore hook for global state compared to React's useState for local component state. Statux's useStore takes a key to identify the global state slice.
```javascript
const [user, setUser] = useState(null); // React Hooks
const [user, setUser] = useStore("user"); // Statux
```
--------------------------------
### Callback-Based Updates with useActions Hook (JavaScript)
Source: https://context7.com/franciscop/statux/llms.txt
Illustrates using callback-based updates with the useActions hook, allowing state modifications based on the current state. This is essential for complex updates like those in a shopping cart where previous state is needed.
```javascript
// Callback-based updates with current state
function ShoppingCart() {
const setCart = useActions("cart");
const addItem = (item) => {
setCart((currentCart) => {
const existingIndex = currentCart.findIndex(i => i.id === item.id);
if (existingIndex >= 0) {
const updated = [...currentCart];
updated[existingIndex] = {
...updated[existingIndex],
quantity: updated[existingIndex].quantity + 1
};
return updated;
}
return [...currentCart, { ...item, quantity: 1 }];
});
};
return (
);
}
```
--------------------------------
### Define Statux Store Structure
Source: https://github.com/franciscop/statux/blob/master/README.md
This JavaScript code illustrates how to define the structure of the application's state using the `` component. It sets initial values for 'id' and 'friends'.
```javascript
// src/App.js
import Store from "statux";
import Navigation from "./Navigation";
// state = { id: null, friends: [] }
export default () => (
);
```
--------------------------------
### Form Submission with API and Statux
Source: https://context7.com/franciscop/statux/llms.txt
This snippet shows how to handle form submissions that involve an API call and update the user state upon successful login. It uses `useState` for form data and submission status, and `useActions` from Statux to dispatch an action that updates the 'user' state. Error handling for the API request is also included.
```javascript
// Form submission with API
function LoginForm() {
const setUser = useActions("user");
const [formData, setFormData] = useState({ email: "", password: "" });
const [submitting, setSubmitting] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
setSubmitting(true);
try {
const response = await fetch("/api/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(formData)
});
if (!response.ok) {
throw new Error("Login failed");
}
const userData = await response.json();
setUser(userData);
} catch (error) {
alert(error.message);
} finally {
setSubmitting(false);
}
};
return (
);
}
```
--------------------------------
### useSelector Hook - Read-Only State Access with Statux
Source: https://context7.com/franciscop/statux/llms.txt
Demonstrates how to use the `useSelector` hook from the 'statux' library to access read-only state fragments. It covers various selection strategies including direct property access, nested properties, function selectors for computed values, multiple state selections, array element selection, and safe nested access with defaults. Components re-render efficiently based on changes in the selected state.
```javascript
import { useSelector } from "statux";
// String selector for direct property access
function UserDisplay() {
const user = useSelector("user");
return (
{user ? (
Logged in as: {user.name}
) : (
Not logged in
)}
);
}
// Nested property selection
function UserEmail() {
const email = useSelector("user.email");
return {email};
}
// Function selector for computed values
function UserGreeting() {
const greeting = useSelector((state) => {
if (!state.user) return "Guest";
return `${state.user.name} (${state.user.role})`;
});
return
);
}
// Array element selection
function BookTitle({ index }) {
const title = useSelector(`books.${index}.title`);
return
{title}
;
}
// Safe nested access with defaults
function UserProfile() {
const profile = useSelector((state) => ({
name: state.user?.name || "Anonymous",
avatar: state.user?.avatar || "/default-avatar.png",
bio: state.user?.bio || "No bio available"
}));
return (
{profile.name}
{profile.bio}
);
}
```
--------------------------------
### Array Manipulation with useActions Hook (JavaScript)
Source: https://context7.com/franciscop/statux/llms.txt
Illustrates array manipulation using the .push(), .pop(), .shift(), and .unshift() methods provided by the useActions hook. These methods allow for immutable addition and removal of elements from the beginning and end of an array.
```javascript
// Array manipulation - push, pop, shift, unshift
function TodoList() {
const setTodos = useActions("todos");
const addTodo = (text) => {
setTodos.push({ id: Date.now(), text, done: false });
};
const removeLastTodo = () => setTodos.pop();
const removeFirstTodo = () => setTodos.shift();
const addToStart = (text) => {
setTodos.unshift({ id: Date.now(), text, done: false });
};
return (
);
}
```
--------------------------------
### Extracting and Using useActions Helper Methods
Source: https://github.com/franciscop/statux/blob/master/README.md
This code snippet shows how helper methods from useActions can be either used directly from the returned action object or extracted individually. This provides flexibility in how state modification functions are accessed and utilized within a component.
```javascript
const BookForm = () => {
const setBooks = useActions("books");
const onSubmit = (book) => setBooks.append(book);
// OR
const { append } = useActions("books");
const onSubmit = (book) => append(book);
return ;
};
```
--------------------------------
### Array Fill with useActions Hook (JavaScript)
Source: https://context7.com/franciscop/statux/llms.txt
Details how to fill an array with a specific value or within a range using the .fill() method of the useActions hook. This is useful for resetting array elements or initializing parts of an array immutably.
```javascript
// Fill array with specific value
function ResetList() {
const setScores = useActions("scores");
const resetAll = () => setScores.fill(0);
const fillRange = () => setScores.fill(100, 2, 5); // Fill indices 2-4
return (
);
}
```
--------------------------------
### Object Manipulation with useActions Hook (JavaScript)
Source: https://context7.com/franciscop/statux/llms.txt
Demonstrates how to use the .assign() and .remove() methods of the useActions hook for immutable object updates. This includes adding new properties, updating existing ones, and removing properties from an object.
```javascript
import { useActions } from "statux";
// Object manipulation with .assign() and .remove()
function UserEditor() {
const setUser = useActions("user");
const updateName = (name) => setUser.assign({ name });
const updateEmail = (email) => setUser.assign({ email });
const removeAvatar = () => setUser.remove("avatar");
const addPremium = () => setUser.assign({
premium: true,
premiumSince: new Date().toISOString()
});
return (
);
}
```
--------------------------------
### Modifying State with assign Helper (Statux)
Source: https://github.com/franciscop/statux/blob/master/README.md
Illustrates using the `.assign()` helper method provided by Statux for updating specific properties of an object in the global state. This is a concise way to perform partial updates.
```javascript
const onClick = (name) => setUser.assign({ name });
```
--------------------------------
### API Calls on User Action with Statux and Axios
Source: https://github.com/franciscop/statux/blob/master/README.md
This snippet shows how to trigger API calls in response to user actions, specifically a login form submission. It uses `axios` for making the HTTP POST request and `form-mate` for handling form data. The `useActions` hook from Statux is used to update the user state upon successful login.
```javascript
// LoginForm.js
import { useActions } from "statux";
import axios from "axios";
import Form from "form-mate";
export default () => {
const setUser = useActions("user");
const onSubmit = async (data) => {
const { data } = await axios.post("/login", data);
setUser(data);
};
return (
);
};
```
--------------------------------
### Adding to an Array State with append Helper (Statux)
Source: https://github.com/franciscop/statux/blob/master/README.md
Demonstrates using the `.append()` helper method in Statux to add an item to an array in the global state. This provides a convenient and readable way to append elements.
```javascript
const onSubmit = (book) => setBooks.append(book);
```
--------------------------------
### Adding to an Array State with Spread Syntax and Callback (Statux)
Source: https://github.com/franciscop/statux/blob/master/README.md
Shows how to immutably add a new item to an array stored in Statux's global state, using both direct spread syntax and a callback function for the update.
```javascript
// Add a book to the list
const onSubmit = (book) => setBooks([...books, book]);
const onSubmit = (book) => setBooks((books) => [...books, book]);
```
--------------------------------
### useStore Hook - Access and Modify State
Source: https://context7.com/franciscop/statux/llms.txt
The `useStore()` hook provides access to a slice of the global state and a function to update it, mirroring React's `useState`. It supports string selectors for nested properties and callback setters for state-based updates.
```APIDOC
## useStore Hook - Access and Modify State
### Description
The `useStore()` hook returns an array containing the current state slice and a setter function, similar to React's `useState()`. It accepts a string selector using dot notation to access nested properties or array indices.
### Method
React Hook
### Endpoint
N/A (Hook)
### Parameters
#### Arguments
- **`selector`** (string) - Required - A string path to the state slice (e.g., 'user', 'user.name', 'books.0').
### Return Value
- **`stateSlice`** (any) - The current value of the selected state slice.
- **`setState`** (function) - A function to update the state slice. It can accept a new value or a callback function for state-based updates.
### Request Example
```javascript
import { useStore } from "statux";
// Basic usage - entire state fragment
function UserProfile() {
const [user, setUser] = useStore("user");
const login = () => setUser({ id: 1, name: "John", email: "john@example.com" });
const logout = () => setUser(null);
if (!user) {
return ;
}
return (
);
}
```
### Response
N/A (Hook returns state and setter)
```
--------------------------------
### Advanced Array Splice with useActions Hook (JavaScript)
Source: https://context7.com/franciscop/statux/llms.txt
Explains how to perform advanced array manipulations like inserting, replacing, and removing elements within a range using the .splice() method from the useActions hook. This allows for precise control over array contents immutably.
```javascript
// Array splice for advanced manipulation
function ItemEditor() {
const setItems = useActions("items");
const insertAt = (index, item) => {
setItems.splice(index, 0, item);
};
const replaceAt = (index, newItem) => {
setItems.splice(index, 1, newItem);
};
const removeRange = (start, count) => {
setItems.splice(start, count);
};
return (
);
}
```
--------------------------------
### Accessing State with Default Values (Statux)
Source: https://github.com/franciscop/statux/blob/master/README.md
Shows how to safely access state properties with default values in Statux when the state might be undefined or null. This avoids errors when dealing with potentially missing data.
```javascript
const App = () => {
const [user] = useStore("user");
const name = user.name || "John";
return
{name}
;
};
```
--------------------------------
### Array Transformation with useActions Hook (JavaScript)
Source: https://context7.com/franciscop/statux/llms.txt
Demonstrates transforming arrays using .sort(), .filter(), and .map() methods from the useActions hook for immutable operations. This includes sorting by a property, filtering based on a condition, and mapping elements to new values.
```javascript
// Array sorting, filtering, and mapping
function ProductList() {
const setProducts = useActions("products");
const sortByPrice = () => {
setProducts.sort((a, b) => a.price - b.price);
};
const filterInStock = () => {
setProducts.filter(product => product.stock > 0);
};
const applyDiscount = (percentage) => {
setProducts.map(product => ({
...product,
price: product.price * (1 - percentage / 100)
}));
};
const reverseOrder = () => setProducts.reverse();
return (
);
}
```
--------------------------------
### Use useStore Hook for State Management
Source: https://github.com/franciscop/statux/blob/master/README.md
This JavaScript code shows how to use the `useStore` hook from Statux to access and update state within a React component. It retrieves the 'user' state and provides a function to update it.
```javascript
// src/User.js
import { useStore } from "statux";
export default () => {
const [user, setUser] = useStore("user");
const login = () => setUser({ name: "Maria" });
return (
Hello {user ? user.name : }
);
};
```
--------------------------------
### Array State Modification with useActions Helpers
Source: https://github.com/franciscop/statux/blob/master/README.md
This snippet illustrates the use of various helper methods provided by useActions for modifying array state. These methods are inspired by JavaScript's built-in Array prototype methods, allowing for operations like filling, pushing, popping, sorting, and more.
```javascript
// For the state of: books = ['a', 'b', 'c']
const { fill, pop, push, ...setBooks } = useActions("books");
fill(1); // [1, 1, 1]
pop(); // ['a', 'b']
push("d"); // ['a', 'b', 'c', 'd']
setBooks.reverse(); // ['c', 'b', 'a']
setBooks.shift(); // ['b', 'c']
setBooks.sort(); // ['a', 'b', 'c']
setBooks.splice(1, 1, "x"); // ['a', 'x', 'c']
setBooks.unshift("x"); // ['x', 'a', 'b', 'c']
// Aliases
setBooks.append("x"); // ['a', 'b', 'c', 'x']
setBooks.prepend("x"); // ['x', 'a', 'b', 'c']
setBooks.remove(1); // ['a', 'c']
// These are immutable, but this still helps:
setBooks.concat("d", "e"); // ['a', 'b', 'c', 'd', 'e']
setBooks.slice(1, 1); // ['b']
setBooks.filter((item) => /^(a|b)$/.test(item)); // ['a', 'b']
setBooks.map((book) => book + "!"); // ['a!', 'b!', 'c!']
setBooks.reduce((all, book) => [...all, book + "x"], []); // ['ax', 'bx', 'cx']
setBooks.reduceRight((all, book) => [...all, book], []); // ['c', 'b', 'a']
```
--------------------------------
### useStore Hook for State Subtree Management (JavaScript)
Source: https://github.com/franciscop/statux/blob/master/README.md
The `useStore` hook from Statux manages a state subtree in React. It accepts a string selector and returns an array similar to React's `useState`, containing the state fragment and a setter function. The setter can be used to update the state with plain objects, functions, or by assigning specific properties.
```javascript
import { useStore } from "statux";
export default () => {
const [user, setUser] = useStore("user");
return (
);
};
```
```javascript
import { useStore } from "statux";
export default () => {
// If `user` is null, this will throw an error
const [name = "Anonymous", setName] = useStore("user.name");
return
setName("John")}>{name}
;
};
```
```javascript
const [user, setUser] = useStore("user");
// Same as
// const user = useSelector("user");
// const setUser = useActions("user");
```
```javascript
// Plain object to update it
setUser({ ...user, name: "Francisco" });
// Function that accepts the current user
setUser((user) => ({ ...user, name: "Francisco" }));
// Modify only the specified props
setUser.assign({ name: "Francisco" });
```
--------------------------------
### Accessing Nested State with Default Values (Statux)
Source: https://github.com/franciscop/statux/blob/master/README.md
Demonstrates accessing a nested property of the global state in Statux, providing a default value if the property or its parent is not defined. This uses dot notation for accessing nested state.
```javascript
const App = () => {
const [name = "John"] = useStore("user.name");
return