### Create Stan-js Store (JavaScript) Source: https://codemask-labs.github.io/stan-js/examples/react-astro This snippet shows how to initialize a store using Stan-js. It defines the initial state and exposes the store's state, actions, and effects for use in applications. Dependencies include the 'stan-js' library. ```javascript import { createStore } from 'stan-js' export const { useStore, getState, actions, effect } = createStore({ counter: 0, }) ``` -------------------------------- ### Install stan-js with npm, yarn, pnpm, bun Source: https://codemask-labs.github.io/stan-js/guides/introduction Installs the stan-js library using different package managers. Choose the command corresponding to your preferred package manager. ```bash npm install stan-js ``` ```bash yarn add stan-js ``` ```bash pnpm add stan-js ``` ```bash bun add stan-js ``` -------------------------------- ### Install stan-js-devtools using bun Source: https://codemask-labs.github.io/stan-js/guides/devtools Install the stan-js-devtools package using bun. This command adds the necessary dependencies to your project for state managementdevtools. ```bash bun add stan-js-devtools ``` -------------------------------- ### Initial stan-js Store Setup Source: https://codemask-labs.github.io/stan-js/reference/destructure Demonstrates a basic stan-js store setup with a computed property 'isAuthenticated'. This initial version might not immediately reveal potential issues related to proxy observation. ```typescript export const store = createStore({ accessToken: null as string | null, userInfo: null as UserInfo | null, get isAuthenticated() { return Boolean(this.accessToken) && Boolean(this.userInfo) } }) ``` -------------------------------- ### Create Stan-JS Scoped Store Source: https://codemask-labs.github.io/stan-js/examples/tanstack-start This snippet demonstrates how to create a scoped store using `createScopedStore` from the 'stan-js' library. It defines initial state values for 'user' and 'counter'. The returned object provides a `StoreProvider` to wrap your application and hooks (`useScopedStore`, `useStore`) to access the store. ```javascript import { createScopedStore } from 'stan-js' export const { StoreProvider, useScopedStore, useStore } = createScopedStore({ user: '', counter: 0, }) ``` -------------------------------- ### Create Store with Storage in React Source: https://codemask-labs.github.io/stan-js/reference/synchronizer Demonstrates how to create a store using Stan-JS's `createStore` and integrate persistent storage using the `storage` utility. It shows initializing a counter with a specific storage key and a user field that defaults to undefined. This setup ensures that 'counter' and 'user' values are persisted across sessions. ```javascript import { createStore } from 'stan-js' import { storage } from 'stan-js/storage' const { useStore } = createStore({ counter: storage(0, { storageKey: 'counter-key' }), // number user: storage(), // string | undefined cart: [] as Array }) ``` -------------------------------- ### Install stan-js-devtools using npm Source: https://codemask-labs.github.io/stan-js/guides/devtools Install the stan-js-devtools package using npm. This command adds the necessary dependencies to your project for state managementdevtools. ```bash npm install stan-js-devtools ``` -------------------------------- ### Install stan-js-devtools using pnpm Source: https://codemask-labs.github.io/stan-js/guides/devtools Install the stan-js-devtools package using pnpm. This command adds the necessary dependencies to your project for state managementdevtools. ```bash pnpm add stan-js-devtools ``` -------------------------------- ### Install stan-js-devtools using yarn Source: https://codemask-labs.github.io/stan-js/guides/devtools Install the stan-js-devtools package using yarn. This command adds the necessary dependencies to your project for state managementdevtools. ```bash yarn add stan-js-devtools ``` -------------------------------- ### Tanstack Router Root Route with StoreProvider Integration Source: https://codemask-labs.github.io/stan-js/examples/tanstack-start This code defines the root route for a Tanstack Router application. It fetches user data using a server function and then passes the fetched user and counter from search params as initial values to the `StoreProvider` from Stan-JS. This ensures the store is initialized with data before the rest of the application renders. ```javascript import { createRootRoute, HeadContent, Outlet, Scripts, } from '@tanstack/react-router' import { createServerFn } from '@tanstack/react-start' import { z } from 'zod' import { fetchUser } from '../data' import globals from '../globals.css?url' import { StoreProvider } from '../store' const RootComponent = () => { const { user } = Route.useLoaderData() const { counter } = Route.useSearch() return ( ) } const getUser = createServerFn({ method: 'GET' }).handler(fetchUser) export const Route = createRootRoute({ head: () => ({ meta: [ { charSet: 'utf-8', }, { name: 'viewport', content: 'width=device-width, initial-scale=1', }, { title: 'TanStack Start Starter', }, ], links: [ { rel: 'stylesheet', href: globals }, ], }), component: RootComponent, loader: async () => { const user = await getUser() return { user, } }, validateSearch: z.object({ counter: z.number().optional(), }), }) ``` -------------------------------- ### Recommended stan-js Store Setup with Destructuring Source: https://codemask-labs.github.io/stan-js/reference/destructure Demonstrates the recommended approach for defining computed properties in stan-js using destructuring assignment. This method ensures all accessed properties are properly observed by stan-js's proxy mechanism, avoiding subscription issues. ```typescript export const store = createStore({ accessToken: null as string | null, userInfo: null as UserInfo | null, get isAuthenticated() { const { accessToken, userInfo } = this return Boolean(accessToken) && Boolean(userInfo) } }) ``` -------------------------------- ### Stan.js Store Setup with Counter, Message, and Users Source: https://codemask-labs.github.io/stan-js/examples/react Configuration of the `stan-js` store, defining initial state for a counter, a message, and an array for users. It also includes a computed property `upperCaseMessage` and sets up a timer to update `currentTime` every second. ```ts import { createStore } from 'stan-js' export const { useStore, reset, getState, actions } = createStore({ counter: 0, message: 'Hello, Stan!', get upperCaseMessage() { return this.message.toUpperCase() }, currentTime: new Date(), users: [] as string[], }) setInterval(() => { actions.setCurrentTime(new Date()) }, 1000) export const fetchUsers = async () => { try { const res = await fetch('https://randommer.io/Name', { headers: { 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8', }, body: 'type=firstname&number=20', method: 'POST', }) const data = await res.json() return data as string[] } catch { return [] } } ``` -------------------------------- ### Tanstack Router File Route Accessing Stan-JS Store Source: https://codemask-labs.github.io/stan-js/examples/tanstack-start This snippet defines a file route in Tanstack Router and demonstrates how to access the global store created by Stan-JS using the `useStore` hook. It retrieves the 'user' state from the store and displays it in a greeting. It also includes a `Counter` component, which implies interaction with the store's state. ```javascript import { createFileRoute } from '@tanstack/react-router' import { Counter } from '../components/Counter' import { useStore } from '../store' const Home = () => { const { user } = useStore() return (

Hello {user}!

) } export const Route = createFileRoute('/')({ component: Home, }) ``` -------------------------------- ### Create Computed Value Based on Store Value Source: https://codemask-labs.github.io/stan-js/examples/react This example illustrates how to create a computed value that is derived from another value stored within a state management system. This pattern is useful for deriving UI elements or performing calculations based on application state. It implies the use of a store or state management library. ```javascript // Assuming 'store' is an object with state and a way to define computed values const computedValue = store.computed(() => { return store.state.someValue * 2; }); ``` -------------------------------- ### Get Store State with getState Source: https://codemask-labs.github.io/stan-js/reference/createstore Retrieves the current state of the store. This function returns an object containing all state properties. Useful for reading state values without triggering re-renders. ```javascript const { count } = getState() console.log(count) ``` -------------------------------- ### Astro Counter Component (Astro/JavaScript) Source: https://codemask-labs.github.io/stan-js/examples/react-astro An Astro component that displays a counter and provides buttons to increment and decrement its value. It utilizes Stan-js for state management, updating the UI reactively when the counter state changes. It depends on the Stan-js store defined in '../store'. ```astro --- import { getState } from '../store' ---
Astro

Astro Counter

{getState().counter}

``` -------------------------------- ### Fixing stan-js Computed Property Subscription Source: https://codemask-labs.github.io/stan-js/reference/destructure Presents a way to fix the dependency subscription issue in stan-js computed properties by ensuring all relevant properties are accessed, even if indirectly. This example uses Array.prototype.every to check multiple boolean values. ```typescript export const store = createStore({ accessToken: null as string | null, userInfo: null as UserInfo | null, get isAuthenticated() { return [this.accessToken, this.userInfo].every(Boolean) } }) ``` -------------------------------- ### Stan-JS Counter Component Using useStore Hook Source: https://codemask-labs.github.io/stan-js/examples/tanstack-start This component utilizes the `useStore` hook from Stan-JS to access and modify the 'counter' state. It provides buttons to increment and decrement the counter. The `setCounter` function allows for updating the state, potentially using a functional update to ensure atomicity. ```javascript import { useStore } from '../store' export const Counter = () => { const { counter, setCounter } = useStore() return (
{counter}
) } ``` -------------------------------- ### React Fetch More Users Component with Stan.js State Management Source: https://codemask-labs.github.io/stan-js/examples/react A React component that allows users to fetch more users and update the store managed by `stan-js`. It uses an asynchronous function `fetchUsers` to get new user data and appends it to the existing user list in the store. ```tsx import { useStore } from 'stan-js' const FetchMore = () => { const { setUsers } = useStore() const fetchMoreUsers = async () => { const users = await fetchUsers() setUsers(prev => [...prev, ...users]) } return ( ) } ``` -------------------------------- ### React Counter Component (React/JavaScript) Source: https://codemask-labs.github.io/stan-js/examples/react-astro A React functional component that displays a counter and includes buttons for incrementing and decrementing. It uses Stan-js's `useStore` hook to access and update the counter state, ensuring the UI reflects state changes. Dependencies include 'react' and the Stan-js store from '../store'. ```javascript import { useStore } from '../store' export const ReactCounter = () => { const { counter, setCounter } = useStore() return (
React

React Counter

{counter}

) } ``` -------------------------------- ### Preview Project with Vite Source: https://codemask-labs.github.io/stan-js/examples/react This script serves a preview of the built project using Vite. It's useful for testing the production build locally before deployment. ```bash vite preview ``` -------------------------------- ### React Entry Point with react-scan Initialization Source: https://codemask-labs.github.io/stan-js/examples/react The `main.tsx` file sets up the React application entry point. It initializes `react-scan` for potential debugging or development features and then renders the main `App` component into the DOM. ```tsx import { createRoot } from 'react-dom/client' import { scan } from 'react-scan' import './index.css' import { App } from './App.tsx' scan({ enabled: true, alwaysShowLabels: true, }) createRoot(document.getElementById('root')!).render( ) ``` -------------------------------- ### Create Store with stan-js Source: https://codemask-labs.github.io/stan-js/reference/createstore Initializes a store with specified state keys and default values. Actions for updating state are automatically generated. Supports optional persistence via Synchronizer. ```javascript import { createStore } from 'stan-js' export const { actions, getState, reset, effect, useStore, useStoreEffect } = createStore({ count: 0, name: 'John', notifications: [] as Array }) ``` -------------------------------- ### Create a stan-js store with initial state Source: https://codemask-labs.github.io/stan-js/guides/introduction Demonstrates how to create a new store using the `createStore` function from 'stan-js'. It initializes state properties like 'count', 'doubleCounter', 'user', 'selectedLanguage', and 'unreadNotifications'. The 'storage' utility from 'stan-js/storage' is also imported. ```typescript import { createStore } from 'stan-js' import { storage } from 'stan-js/storage' export const { useStore } = createStore({ count: 0, get doubleCounter() { return this.count * 2 }, user: storage(''), selectedLanguage: 'en-US', unreadNotifications: [] as Array }) ``` -------------------------------- ### Build Project with Vite and TypeScript Source: https://codemask-labs.github.io/stan-js/examples/react This script compiles TypeScript projects using 'tsc -b' and then builds the project using Vite. It's essential for creating production-ready assets. ```bash tsc -b && vite build ``` -------------------------------- ### Create Custom Storage with MMKV in React Native Source: https://codemask-labs.github.io/stan-js/reference/synchronizer Illustrates how to create a custom storage solution in React Native using `createStorage` factory function with an encrypted MMKV instance. This allows for secure storage of sensitive data by leveraging MMKV's encryption capabilities. ```javascript import { createStorage } from 'stan-js/storage' import { MMKV } from 'react-native-mmkv' const encryptedMMKV = new MMKV({ encryptionKey: 'my-encryption-key' }) const myStorage = createStorage({ mmkvInstance: encryptedMMKV, }) ``` -------------------------------- ### Lint Project with ESLint Source: https://codemask-labs.github.io/stan-js/examples/react This command lints the entire project using ESLint, helping to maintain code quality and consistency by identifying and reporting on problematic patterns in JavaScript/TypeScript code. ```bash eslint . ``` -------------------------------- ### Custom Storage with SuperJSON Serialization Source: https://codemask-labs.github.io/stan-js/reference/synchronizer Shows how to create a custom storage configuration using `createStorage` with `superjson` for advanced serialization and deserialization. This is useful for storing complex data types like Sets that are not natively supported by JSON. ```javascript import { createStore } from 'stan-js' import { createStorage } from 'stan-js/storage' import superjson from 'superjson' const superJsonStorage = createStorage({ serialize: superjson.stringify, deserialize: superjson.deserialize }) const { useStore } = createStore({ user: superJsonStorage(new Set()) }) ``` -------------------------------- ### Next.js Root Layout with SSR Data Fetching Source: https://codemask-labs.github.io/stan-js/examples/nextjs Sets up the root layout for a Next.js application. It fetches user data on the server using `fetchUser` and provides this initial state to the stan-js store via `StoreProvider` for client-side hydration. ```typescript import { fetchUser, metadata } from '@/data' import { StoreProvider } from '@/store' import './globals.css' const RootLayout = async ({ children }: { children: React.ReactNode }) => { const user = await fetchUser() return ( {children} ) } export default RootLayout export { metadata } ``` -------------------------------- ### TypeScript Project Configuration Source: https://codemask-labs.github.io/stan-js/examples/react Configures the TypeScript compiler for the project. It specifies project references for application and node configurations, and sets up path aliases for easier module resolution within the 'src' directory. ```json { "files": [], "references": [ { "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" } ], "compilerOptions": { "baseUrl": ".", "paths": { "@/*": ["./src/*"] } } } ``` -------------------------------- ### ESLint Configuration (TypeScript) Source: https://codemask-labs.github.io/stan-js/examples/react Configures ESLint for a TypeScript and React project. It extends recommended rules from ESLint and TypeScript ESLint, integrates with `eslint-plugin-react-hooks` and `eslint-plugin-react-refresh`, and specifies browser globals. ```typescript import js from '@eslint/js' import reactHooks from 'eslint-plugin-react-hooks' import reactRefresh from 'eslint-plugin-react-refresh' import globals from 'globals' import tseslint from 'typescript-eslint' export default tseslint.config( { ignores: ['dist'] }, { extends: [js.configs.recommended, ...tseslint.configs.recommended], files: ['**/*.{ts,tsx}'], languageOptions: { ecmaVersion: 2020, globals: globals.browser, }, plugins: { 'react-hooks': reactHooks, 'react-refresh': reactRefresh, }, rules: { ...reactHooks.configs.recommended.rules, 'react-refresh/only-export-components': [ 'warn', { allowConstantExport: true, }, ], }, }, ) ``` -------------------------------- ### Vite Configuration for React and Tailwind CSS Source: https://codemask-labs.github.io/stan-js/examples/react Configures the Vite build tool for a React project with Tailwind CSS integration. It sets up plugins for React and Tailwind, and defines path aliases for module imports, pointing to the 'src' directory. ```typescript import tailwind from '@tailwindcss/vite' import react from '@vitejs/plugin-react' import path from 'path' import { defineConfig } from 'vite' export default defineConfig({ plugins: [ react(), tailwind(), ], resolve: { alias: { '@': path.resolve(__dirname, './src'), }, }, }) ``` -------------------------------- ### Project Dependencies (package-lock.json) Source: https://codemask-labs.github.io/stan-js/examples/react This JSON file lists all the dependencies required for the project, including development dependencies. It specifies exact versions for packages like React, Stan.js, Tailwind CSS, and various ESLint and Vite plugins, ensuring reproducible builds. ```json { "name": "react", "version": "0.0.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "react", "version": "0.0.0", "dependencies": { "@radix-ui/react-slot": "1.1.0", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "lucide-react": "^0.507.0", "react": "18.3.1", "react-dom": "18.3.1", "react-scan": "0.3.3", "stan-js": "latest", "tailwind-merge": "^3.2.0", "tailwindcss-animate": "1.0.7" }, "devDependencies": { "@eslint/js": "9.26.0", "@tailwindcss/vite": "4.1.5", "@types/node": "22.10.1", "@types/react": "18.3.12", "@types/react-dom": "18.3.1", "@vitejs/plugin-react": "4.3.4", "eslint": "9.26.0", "eslint-plugin-react-hooks": "5.2.0", "eslint-plugin-react-refresh": "0.4.20", "globals": "15.12.0", "jiti": "2.4.2", "tailwindcss": "4.1.5", "tw-animate-css": "^1.2.9", "typescript": "5.8.3", "typescript-eslint": "8.31.1", "vite": "6.0.1" } }, "node_modules/@babel/code-frame": { "version": "7.27.1", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.27.1.tgz", "integrity": "sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg==", "dependencies": { "@babel/helper-validator-identifier": "^7.27.1", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/compat-data": { "version": "7.28.5", "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.28.5.tgz", "integrity": "sha512-6uFXyCayocRbqhZOB+6XcuZbkMNimwfVGFji8CTZnCzOHVGvDqzvitu1re2AU5LROliz7eQPhB8CpAMvnx9EjA==", "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/core": { "version": "7.28.5", "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.28.5.tgz", "integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==", "dependencies": { "@babel/code-frame": "^7.27.1", "@babel/generator": "^7.28.5", "@babel/helper-compilation-targets": "^7.27.2", "@babel/helper-module-transforms": "^7.28.3", "@babel/helpers": "^7.28.4", "@babel/parser": "^7.28.5", "@babel/template": "^7.27.2", "@babel/traverse": "^7.28.5", "@babel/types": "^7.28.5", "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", "json5": "^2.2.3", "semver": "^6.3.1" }, "engines": { "node": ">=6.9.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/babel" } }, "node_modules/@babel/generator": { "version": "7.28.5", "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.28.5.tgz", "integrity": "sha512-3EwLFhZ38J4VyIP6WNtt2kUdW9dokXA9Cr4IVIFHuCpZ3H8/YFOl5JjZHisrn1fATPBmKKqXzDFvh9fUwHz6CQ==", "dependencies": { "@babel/parser": "^7.28.5", "@babel/types": "^7.28.5", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-compilation-targets": { "version": "7.27.2", "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.27.2.tgz", "integrity": "sha512-2+1thGUUWWjLTYTHZWK1n8Yga0ijBz1XAhUXcKy81rd5g6yh7hGqMp45v7cadSbEHc9G3OTv45SyneRN3ps4DQ==", "dependencies": { "@babel/compat-data": "^7.27.2", "@babel/helper-validator-option": "^7.27.1", "browserslist": "^4.24.0", "lru-cache": "^5.1.1", "semver": "^6.3.1" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-globals": { "version": "7.28.0", "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.28.0.tgz", "integrity": "sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4h" } } } ``` -------------------------------- ### TypeScript Configuration for Vite Source: https://codemask-labs.github.io/stan-js/examples/react Node.js specific TypeScript configuration for Vite projects. It enables ESNext module support, skips library checks, uses bundler module resolution, allows importing TS extensions, enforces isolated modules, and forces module detection. It also includes strict linting rules and excludes emitting JavaScript files. ```json { "compilerOptions": { "module": "ESNext", "skipLibCheck": true, "moduleResolution": "bundler", "allowImportingTsExtensions": true, "isolatedModules": true, "moduleDetection": "force", "noEmit": true, "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "noUncheckedSideEffectImports": true }, "include": ["vite.config.ts"] } ``` -------------------------------- ### Hydrate Store State with useHydrateState Source: https://codemask-labs.github.io/stan-js/reference/createstore Initializes or updates the store's state with provided values. This function is useful for setting an initial state, perhaps from server-side rendering or local storage. ```javascript const { useHydrateState } = createStore({ count: 0, name: 'John', notifications: [] as Array }) useHydrateState({ count: 10, name: 'Jane', notifications: [{ message: 'Hello' }] }) // Now the store's state is: // count: 10, name: 'Jane', notifications: [{ message: 'Hello' }] ``` -------------------------------- ### Create Scoped Store with Stan-JS Source: https://codemask-labs.github.io/stan-js/examples/nextjs Initializes a scoped store using `createScopedStore` from stan-js. This function sets up the StoreProvider and hooks for accessing the store, defining initial state for 'user' and 'counter'. ```typescript "use client" import { createScopedStore } from 'stan-js' export const { StoreProvider, useScopedStore, useStore } = createScopedStore({ user: '', counter: 0, }) ``` -------------------------------- ### Vite Project Configuration for React and Stan.js Source: https://codemask-labs.github.io/stan-js/examples/react The `package.json` file for a Vite-based React project using `stan-js`. It lists dependencies including `react`, `react-dom`, `stan-js`, `vite`, and `tailwindcss`, along with development dependencies and scripts for building and running the application. ```json { "name": "react", "private": true, "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "build": "tsc -b && vite build", "lint": "eslint .", "preview": "vite preview" }, "stackblitz": { "startCommand": "npm install && npm run dev" }, "dependencies": { "@radix-ui/react-slot": "1.1.0", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "lucide-react": "^0.507.0", "react": "18.3.1", "react-dom": "18.3.1", "react-scan": "0.3.3", "stan-js": "latest", "tailwind-merge": "^3.2.0", "tailwindcss-animate": "1.0.7" }, "devDependencies": { "@eslint/js": "9.26.0", "@tailwindcss/vite": "4.1.5", "@types/node": "22.10.1", "@types/react": "18.3.12", "@types/react-dom": "18.3.1", "@vitejs/plugin-react": "4.3.4", "eslint": "9.26.0", "eslint-plugin-react-hooks": "5.2.0", "eslint-plugin-react-refresh": "0.4.20", "globals": "15.12.0", "jiti": "2.4.2", "tailwindcss": "4.1.5", "tw-animate-css": "^1.2.9", "typescript": "5.8.3", "typescript-eslint": "8.31.1", "vite": "6.0.1" } } ``` -------------------------------- ### Home Page with Stan-JS Store Usage Source: https://codemask-labs.github.io/stan-js/examples/nextjs Defines the home page component that consumes the stan-js store. It displays a greeting using the 'user' state and includes a Counter component, demonstrating how to access and display store values. ```typescript "use client" import { Counter } from '@/Counter' import { useStore } from '@/store' const HomePage = () => { const { user } = useStore() return (

Hello {user}!

) } export default HomePage ``` -------------------------------- ### Shadcn UI Configuration Schema Source: https://codemask-labs.github.io/stan-js/examples/react Defines the configuration schema for Shadcn UI, specifying the project's style ('new-york'), and settings for React Server Components (RSC), TypeScript (tsx), and Tailwind CSS integration. It maps component directories and utility paths. ```json { "$schema": "https://ui.shadcn.com/schema.json", "style": "new-york", "rsc": false, "tsx": true, "tailwind": { "config": "tailwind.config.ts", "css": "src/index.css", "baseColor": "neutral", "cssVariables": true, "prefix": "" }, "aliases": { "components": "@/components", "utils": "@/lib/utils", "ui": "@/components/ui", "lib": "@/lib" } } ``` -------------------------------- ### Subscribe to Store Changes with effect Source: https://codemask-labs.github.io/stan-js/reference/createstore Sets up a callback function that reacts to changes in specific store values. The callback receives the current state and is triggered whenever a subscribed value changes. Returns a dispose function to unsubscribe. ```javascript const dispose = effect(({ count }) => { console.log(count) }) ``` -------------------------------- ### Create Stan.js Store and Define State Source: https://codemask-labs.github.io/stan-js/examples/react This snippet demonstrates how to create a new store using `createStore` from 'stan-js'. It defines initial state properties like 'counter', 'message', and 'users', along with a computed property 'upperCaseMessage' and an action to update 'currentTime'. The store is then exported for use in other parts of the application. ```typescript import { createStore } from 'stan-js' export const { useStore, reset, getState, actions } = createStore({ counter: 0, message: 'Hello, Stan!', get upperCaseMessage() { return this.message.toUpperCase() }, currentTime: new Date(), users: [] as Array, }) setInterval(() => { actions.setCurrentTime(new Date()) }, 1000) ``` -------------------------------- ### Use stan-js store hook in a React component Source: https://codemask-labs.github.io/stan-js/guides/introduction Shows how to integrate the created stan-js store into a React component using the `useStore` hook. It demonstrates accessing state properties like 'user' and 'count', and updating the 'count' state using the provided setter function. ```typescript import { useStore } from './store' const App = () => { const { count, user, setCount } = useStore() return (

Hello {user}!

Count: {count}

) } ``` -------------------------------- ### Reset Store State with reset Source: https://codemask-labs.github.io/stan-js/reference/createstore Resets the store's state to its initial values. Can be used to reset specific keys or the entire store. Batch updates are handled automatically when resetting multiple keys. ```javascript reset('count') // Only count value will be reset reset('name', 'notifications') // name and notifications will be reset reset() // Whole store will be reset ``` -------------------------------- ### Input Component in React Source: https://codemask-labs.github.io/stan-js/examples/react A customizable Input component for React applications, built with TypeScript. It uses React's forwardRef pattern and integrates with utility classes for styling, allowing for flexible input field creation. ```typescript import * as React from 'react' import { cn } from '@/lib/utils' const Input = React.forwardRef>( ({ className, type, ...props }, ref) => { return ( // Input implementation ) }, ) Input.displayName = 'Input' export { Input } ``` -------------------------------- ### Card Component in React Source: https://codemask-labs.github.io/stan-js/examples/react A reusable Card component for React applications, built with TypeScript. It includes variations for header, title, description, content, and footer. It leverages utility classes for styling and follows React's forwardRef pattern for DOM access. ```typescript import * as React from 'react' import { cn } from '@/lib/utils' const Card = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => ( // Card implementation )) Card.displayName = 'Card' const CardHeader = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => ( // CardHeader implementation )) CardHeader.displayName = 'CardHeader' const CardTitle = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => ( // CardTitle implementation )) CardTitle.displayName = 'CardTitle' const CardDescription = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => ( // CardDescription implementation )) CardDescription.displayName = 'CardDescription' const CardContent = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => // CardContent implementation ) CardContent.displayName = 'CardContent' const CardFooter = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => ( // CardFooter implementation )) CardFooter.displayName = 'CardFooter' export { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } ``` -------------------------------- ### Batch Store Updates with batchUpdates Source: https://codemask-labs.github.io/stan-js/reference/createstore Groups multiple state updates into a single operation, preventing intermediate re-renders or effect executions. Useful for synchronizing related state changes. React's `useSyncExternalStore` handles batching automatically in the `useStore` hook. ```javascript const { batchUpdates, effect, actions } = createStore({ firstName: 'John', lastName: 'Doe', }) effect(({ firstName, lastName }) => { console.log(`${firstName} ${lastName}`) }) actions.setFirstName('Jane') // console.log: Jane Doe actions.setLastName('Bar') // console.log: Jane Bar batchUpdates(() => { actions.setFirstName('Mark') actions.setLastName('Smith') // console.log: Mark Smith }) ``` -------------------------------- ### Define and Use Custom Actions with Stan-JS Source: https://codemask-labs.github.io/stan-js/reference/createstore Demonstrates how to create a custom action named `updateUserNotifications` using Stan-JS. This action accepts an array of notifications, updates the store's notifications, sets the user's name based on the first notification, and resets the 'count' state. It shows both direct usage and usage within a React component via `useStore`. ```javascript export const { actions, useStore } = createStore( { count: 0, name: 'John', notifications: [] as Array }, ({ actions, getState, reset }) => ({ updateUserNotifications: (notifications: Array) => { actions.setNotifications([ ...getState().notifications, ...notifications ]) actions.setName(notifications.at(0)?.userName) reset('count') }, }), ) actions.updateUserNotifications([{ message: 'Hello', userName: 'Jane' }]) const { actions } = useStore() actions.updateUserNotifications([{ message: 'Hello from React', userName: 'React' }]) ``` -------------------------------- ### Tailwind CSS Configuration Source: https://codemask-labs.github.io/stan-js/examples/react The `index.css` file configures Tailwind CSS for the project. It imports the base Tailwind CSS, defines custom variants for dark mode, and sets up base styles for the HTML and body elements, including color schemes and radius. ```css @import "tailwindcss"; @custom-variant dark (&:is(.dark *)); @layer base { :root { --background: 0 0% 100%; --foreground: 0 0% 3.9%; --card: 0 0% 100%; --card-foreground: 0 0% 3.9%; --popover: 0 0% 100%; --popover-foreground: 0 0% 3.9%; --primary: 0 0% 9%; --primary-foreground: 0 0% 98%; --secondary: 0 0% 96.1%; --secondary-foreground: 0 0% 9%; --muted: 0 0% 96.1%; --muted-foreground: 0 0% 45.1%; --accent: 0 0% 96.1%; --accent-foreground: 0 0% 9%; --destructive: 0 84.2% 60.2%; --destructive-foreground: 0 0% 98%; --border: 0 0% 89.8%; --input: 0 0% 89.8%; --ring: 0 0% 3.9%; --chart-1: 12 76% 61%; --chart-2: 173 58% 39%; --chart-3: 197 37% 24%; --chart-4: 43 74% 66%; --chart-5: 27 87% 67%; --radius: 0.5rem; } .dark { --background: 0 0% 3.9%; --foreground: 0 0% 98%; --card: 0 0% 3.9%; --card-foreground: 0 0% 98%; --popover: 0 0% 3.9%; --popover-foreground: 0 0% 98%; --primary: 0 0% 98%; --primary-foreground: 0 0% 9%; --secondary: 0 0% 14.9%; --secondary-foreground: 0 0% 98%; --muted: 0 0% 14.9%; --muted-foreground: 0 0% 63.9%; --accent: 0 0% 14.9%; --accent-foreground: 0 0% 98%; --destructive: 0 62.8% 30.6%; --destructive-foreground: 0 0% 98%; --border: 0 0% 14.9%; --input: 0 0% 14.9%; --ring: 0 0% 83.1%; --chart-1: 220 70% 50%; --chart-2: 160 60% 45%; --chart-3: 30 80% 55%; --chart-4: 280 65% 60%; --chart-5: 340 75% 55%; } } @layer base { * { @apply border-border; } body { @apply bg-background text-foreground; } } @theme inline { --radius-sm: calc(var(--radius) ``` -------------------------------- ### React Component: Fetch More Users Button Source: https://codemask-labs.github.io/stan-js/examples/react This React component features a button that, when clicked, triggers the fetching of more users using the `fetchUsers` function. It then updates the 'users' state in the stan.js store by appending the newly fetched users to the existing list. This demonstrates asynchronous data fetching and state updates within a React component. ```typescript const FetchMore = () => { const { setUsers } = useStore() const fetchMoreUsers = async () => { const users = await fetchUsers() setUsers(prev => [...prev, ...users]) } return ( ) } ``` -------------------------------- ### Create Scoped Store - Stan.js Source: https://codemask-labs.github.io/stan-js/reference/scoped-store This snippet demonstrates how to create a scoped store using `createScopedStore` from the 'stan-js' library. It exports essential components and hooks for managing the scoped state within a React application, particularly useful for SSR scenarios where route-specific state is required. The initial state is defined with a 'count' property initialized to 0. ```javascript import { createScopedStore } from 'stan-js' export const { StoreProvider, useScopedStore, withStore, useStore, useStoreEffect } = createScopedStore({ count: 0, }) ``` -------------------------------- ### Main React Application Component Source: https://codemask-labs.github.io/stan-js/examples/react The main `App` component of the React application, which orchestrates the various UI elements and state management interactions. It uses stan.js hooks (`useStore`, `getState`, `reset`, `actions`) and includes components for displaying and controlling the counter, managing messages, and fetching/displaying users. The layout is structured using Tailwind CSS classes. ```typescript export const App = () => (
Updates & Reset Automatically generated functions for updates and reset. Asynchronous updates Asynchronus updates works without any additional code. Updates outside of React Update the state outside of React without any issues. ``` -------------------------------- ### Fetch Users from External API Source: https://codemask-labs.github.io/stan-js/examples/react This asynchronous function, `fetchUsers`, is responsible for fetching a list of names from an external API ('https://randommer.io/Name'). It makes a POST request with specific body parameters and handles potential errors by returning an empty array. This function is intended to be used with the stan.js store to update the 'users' state. ```typescript export const fetchUsers = async () => { try { const res = await fetch('https://randommer.io/Name', { headers: { 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8', }, body: 'type=firstname&number=20', method: 'POST', }) const data = await res.json() return data as Array } catch { return [] } } ``` -------------------------------- ### React App Integration with Stan.js Store Source: https://codemask-labs.github.io/stan-js/examples/react The main `App` component in React that utilizes the `stan-js` store. It integrates the Counter, UsersList, and FetchMore components, demonstrating various features like automatic updates, asynchronous operations, and state updates outside of React. ```tsx import { CounterControls } from './CounterControls' import { UsersList } from './UsersList' import { FetchMore } from './FetchMore' export const App = () => ( <> ) ```