@fluxmodels/react
TypeScript icon, indicating that this package has built-in type declarations

0.0.5 • Public • Published

FluxModels

type-safe state management


npm react website license: MIT donate

 

Installation

React:

npm install @fluxmodels/react
# or
yarn add @fluxmodels/react

 

TypeScript configuration

To use FluxModels with TypeScript, you need to enable experimental decorators and emit decorator metadata in your tsconfig.json file.

Add the following configurations:

{
    "compilerOptions": {
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        // ... other options
    }
}

These settings allow TypeScript to properly handle the decorators used in FluxModels and ensure full functionality of the library.

 

Basic Usage (React)

import React from 'react'
import { useModel } from '@fluxmodels/react'

const UserModel = {
    username: ''
}

function UsernameInput() {
    const [user, updateUser] = useModel(UserModel)

    return <input 
        value={user.username} 
        onChange={(e) => 
            updateUser({ username: e.target.value })
        } 
    />
}

function App() {
    return <UsernameInput />
}

 

More complex example:

import React, { Suspense } from 'react'

import { STRING } from 'metatyper'
import { useModel, OnInit, UseSuspense, getKey } from '@fluxmodels/react'
class UserModel {
    id = ''
    username = STRING({ maxLength: 12, default: '' })

    async loadUserData({ userID }) {
        // Here could be your API call
        await new Promise((resolve) => setTimeout(resolve, 1000))

        const userData = {
            id: userID,
            username: 'user_' + userID
        }

        Object.assign(this, userData)
    }

    @OnInit() // calc this before render
    @UseSuspense() // will use Suspense until loaded
    async loadUser() {
        const userID = getKey(this)

        await this.loadUserData({ userID })
    }
}
function UserComponent({ userID }) {
    const [user] = useModel(UserModel, { key: userID })

    return (
        <div>
            <p>ID: {user.id}</p>
            <p>Username: {user.username}</p>
            <br />
            <button onClick={() => user.loadUser()}>Load user again</button>
        </div>
    )
}
function App() {
    return (
        <Suspense fallback={<p>Loading...</p>}>
            <UserComponent userID="1" />
            <br />
            <UserComponent userID="2" />
        </Suspense>
    )
}

 

Documentation

For full documentation, visit fluxmodels.dev.

Package Sidebar

Install

npm i @fluxmodels/react

Weekly Downloads

192

Version

0.0.5

License

MIT

Unpacked Size

19 kB

Total Files

10

Last publish

Collaborators

  • vadzimsharai