2.5.3 ā€¢ Published 5 years ago

react-modelx v2.5.3

Weekly downloads
2
License
MIT
Repository
github
Last release
5 years ago

react-model Ā· GitHub license npm version minified size Build Status size downloads Coverage Status Greenkeeper badge PRs Welcome

The State management library for React

šŸŽ‰ Support Both Class and Hooks Api

āš” Fully TypeScript Support

šŸ“¦ built with microbundle

āš™ļø Middlewares Pipline ( redux-devtools support ... )

ā˜‚ļø 100% test coverage, safe on production

šŸ› Debug easily on test environment

Debug Easily


Quick Start

CodeSandbox: TodoMVC

Next.js + react-model work around

install package

npm install react-model

Table of Contents

Core Concept

Model Register

react-model keep the state and actions in a global store. So you need to register them before using.

model/index.model.ts

import { Model } from 'react-model'
import Home from '../model/home.model'
import Shared from '../model/shared.model'

const models = { Home, Shared }

export const { getInitialState, useStore, getState, getActions } = Model(models)
export type Models = typeof models

ā‡§ back to top

useStore

The functional component in React ^16.8.0 can use Hooks to connect the global store. The actions return from useStore can invoke the dom changes.

The execution of actions returned by useStore will invoke the rerender of current component first.

It's the only difference between the actions returned by useStore and getActions now.

import React from 'react'
import { useStore } from '../index.model'

// CSR
export default () => {
  const [state, actions] = useStore('Home')
  const [sharedState, sharedActions] = useStore('Shared')

  return (
    <div>
      Home model value: {JSON.stringify(state)}
      Shared model value: {JSON.stringify(sharedState)}
      <button onClick={e => actions.increment(33)}>home increment</button>
      <button onClick={e => sharedActions.increment(20)}>
        shared increment
      </button>
      <button onClick={e => actions.get()}>fake request</button>
      <button onClick={e => actions.openLight()}>fake nested call</button>
    </div>
  )
}

optional solution on huge dataset (example: TodoList(10000+ Todos)):

  1. use useStore on the subComponents which need it.
  2. use useStore with depActions and React.memo to prevent child components rerender frequently.

Demo Repo

ā‡§ back to top

Model

Every model have their own state and actions.

const initialState = {
  counter: 0,
  light: false,
  response: {} as {
    code: number
    message: string
  }
}

type StateType = typeof initialState
type ActionsParamType = {
  increment: number
  openLight: undefined
  get: undefined
} // You only need to tag the type of params here !

const Model: ModelType<StateType, ActionsParamType> = {
  actions: {
    increment: async (state, _, params) => {
      return {
        counter: state.counter + (params || 1)
      }
    },
    openLight: async (state, actions) => {
      await actions.increment(1) // You can use other actions within the model
      await actions.get() // support async functions (block actions)
      actions.get()
      await actions.increment(1) // + 1
      await actions.increment(1) // + 2
      await actions.increment(1) // + 3 as expected !
      return { light: !state.light }
    },
    get: async () => {
      await new Promise((resolve, reject) =>
        setTimeout(() => {
          resolve()
        }, 3000)
      )
      return {
        response: {
          code: 200,
          message: `${new Date().toLocaleString()} open light success`
        }
      }
    }
  },
  state: initialState
}

export default Model

// You can use these types when use Class Components.
// type ConsumerActionsType = getConsumerActionsType<typeof Model.actions>
// type ConsumerType = { actions: ConsumerActionsType; state: StateType }
// type ActionType = ConsumerActionsType
// export { ConsumerType, StateType, ActionType }

ā‡§ back to top

getState

Key Point: State variable not updating in useEffect callback

To solve it, we provide a way to get the current state of model: getState

Note: the getState method cannot invoke the dom changes automatically by itself.

Hint: The state returned should only be used as readonly

import { useStore, getState } from '../model/index.model'

const BasicHook = () => {
  const [state, actions] = useStore('Counter')
  useEffect(() => {
    console.log('some mounted actions from BasicHooks')
    return () =>
      console.log(
        `Basic Hooks unmounted, current Counter state: ${JSON.stringify(
          getState('Counter')
        )}`
      )
  }, [])
  return (
    <>
      <div>state: {JSON.stringify(state)}</div>
    </>
  )
}

ā‡§ back to top

getActions

You can call other models' actions with getActions api

getActions can be used in both class components and functional components.

import { getActions } from './index.model'

const sharedActions = getActions('Shared')
const counterActions = getActions('Counter')

const model = {
  state: {},
  actions: {
    crossModelCall: () => {
      sharedActions.changeTheme('dark')
      counterActions.increment(9)
    }
  }
}

export default model

ā‡§ back to top

Advance Concept

immutable Actions

The actions use immer produce API to modify the Store. You can return a producer in action.

Using function as return value can make your code cleaner when you modify the deep nested value.

TypeScript Example

// StateType and ActionsParamType definition
// ...

const Model: ModelType<StateType, ActionsParamType> = {
  actions: {
    increment: async (s, _, params) => {
      // issue: https://github.com/Microsoft/TypeScript/issues/29196
      // async function return produce need define type manually.
      return (state: typeof s) => {
        state.counter += params || 1
      }
    },
    decrease: (s, _, params) => s => {
      s.counter += params || 1
    }
  }
}

JavaScript Example

const Model = {
  actions: {
    increment: async (s, _, params) => {
      return state => {
        state.counter += params || 1
      }
    }
  }
}

ā‡§ back to top

SSR with Next.js

shared.model.ts

const initialState = {
  counter: 0
}

const Model: ModelType<StateType, ActionsParamType> = {
  actions: {
    increment: (state, _, params) => {
      return {
        counter: state.counter + (params || 1)
      }
    }
  },
  // Provide for SSR
  asyncState: async context => {
    await waitFor(4000)
    return { counter: 500 }
  },
  state: initialState
}

_app.tsx

import { models, getInitialState, Models } from '../model/index.model'

let persistModel: any

interface ModelsProps {
  initialModels: Models
  persistModel: Models
}

const MyApp = (props: ModelsProps) => {
  if ((process as any).browser) {
    // First come in: initialModels
    // After that: persistModel
    persistModel = props.persistModel || Model(models, props.initialModels)
  }
  const { Component, pageProps, router } = props
  return (
    <Container>
      <Component {...pageProps} />
    </Container>
  )
}

MyApp.getInitialProps = async (context: NextAppContext) => {
  if (!(process as any).browser) {
    const initialModels = context.Component.getInitialProps
      ? await context.Component.getInitialProps(context.ctx)
      await getInitialState() // get all model initialState
      // : await getInitialState({ modelName: 'Home' }) // get Home initialState only
      // : await getInitialState({ modelName: ['Home', 'Todo'] }) // get multi initialState
      // : await getInitialState({ data }) // You can also pass some public data as asyncData params.
    return { initialModels }
  } else {
    return { persistModel }
  }
}

hooks/index.tsx

import { useStore, getState } from '../index.model'
export default () => {
  const [state, actions] = useStore('Home')
  const [sharedState, sharedActions] = useStore('Shared')

  return (
    <div>
      Home model value: {JSON.stringify(state)}
      Shared model value: {JSON.stringify(sharedState)}
      <button
        onClick={e => {
          actions.increment(33)
        }}
      >
    </div>
  )
}

benchmark.tsx

// ...
Benchmark.getInitialProps = async () => {
  return await getInitialState({ modelName: 'Todo' })
}

ā‡§ back to top

Middleware

We always want to try catch all the actions, add common request params, connect Redux devtools and so on. We Provide the middleware pattern for developer to register their own Middleware to satisfy the specific requirement.

// Under the hood
const tryCatch: Middleware<{}> = async (context, restMiddlewares) => {
  const { next } = context
  await next(restMiddlewares).catch((e: any) => console.log(e))
}

// ...

let actionMiddlewares = [
  tryCatch,
  getNewState,
  setNewState,
  stateUpdater,
  communicator,
  devToolsListener
]

// ...
// How we execute an action
const consumerAction = (action: Action) => async (params: any) => {
  const context: Context = {
    modelName,
    setState,
    actionName: action.name,
    next: () => {},
    newState: null,
    params,
    consumerActions,
    action
  }
  await applyMiddlewares(actionMiddlewares, context)
}

// ...

export { ... , actionMiddlewares}

āš™ļø You can override the actionMiddlewares and insert your middleware to specific position

ā‡§ back to top

Other Concept required by Class Component

Provider

The global state standalone can not effect the react class components, we need to provide the state to react root component.

import { PureComponent } from 'react'
import { Provider } from 'react-model'

class App extends PureComponent {
  render() {
    return (
      <Provider>
        <Counter />
      </Provider>
    )
  }
}

ā‡§ back to top

connect

We can use the Provider state with connect.

Javascript decorator version

import React, { PureComponent } from 'react'
import { Provider, connect } from 'react-model'

const mapProps = ({ light, counter }) => ({
  lightStatus: light ? 'open' : 'close',
  counter
}) // You can map the props in connect.

@connect(
  'Home',
  mapProps
)
export default class JSCounter extends PureComponent {
  render() {
    const { state, actions } = this.props
    return (
      <>
        <div>states - {JSON.stringify(state)}</div>
        <button onClick={e => actions.increment(5)}>increment</button>
        <button onClick={e => actions.openLight()}>Light Switch</button>
      </>
    )
  }
}

TypeScript Version

import React, { PureComponent } from 'react'
import { Provider, connect } from 'react-model'
import { StateType, ActionType } from '../model/home.model'

const mapProps = ({ light, counter, response }: StateType) => ({
  lightStatus: light ? 'open' : 'close',
  counter,
  response
})

type RType = ReturnType<typeof mapProps>

class TSCounter extends PureComponent<
  { state: RType } & { actions: ActionType }
> {
  render() {
    const { state, actions } = this.props
    return (
      <>
        <div>TS Counter</div>
        <div>states - {JSON.stringify(state)}</div>
        <button onClick={e => actions.increment(3)}>increment</button>
        <button onClick={e => actions.openLight()}>Light Switch</button>
        <button onClick={e => actions.get()}>Get Response</button>
        <div>message: {JSON.stringify(state.response)}</div>
      </>
    )
  }
}

export default connect(
  'Home',
  mapProps
)(TSCounter)

ā‡§ back to top

FAQ

How can I disable the console debugger?

Just remove consoleDebugger middleware.

import { actionMiddlewares } from 'react-model'
// Find the index of middleware
const consoleDebuggerMiddlewareIndex = actionMiddlewares.indexOf(
  middlewares.consoleDebugger
)
// Remove it
actionMiddlewares.splice(consoleDebuggerMiddlewareIndex, 1)
2.5.3

5 years ago

2.5.2

5 years ago

2.5.1

5 years ago

2.5.0

5 years ago

2.4.2

5 years ago

2.4.1

5 years ago

2.4.1-unstable.2

5 years ago

2.4.1-unstable.1

5 years ago

2.4.1-unstable.0

5 years ago

2.4.1-unstable

5 years ago

2.4.0

5 years ago

2.3.2

5 years ago

2.3.1

5 years ago

2.3.0-unstable

5 years ago

2.3.0

5 years ago

2.2.2

5 years ago

2.2.2-unstable.2

5 years ago

2.2.2-unstable.1

5 years ago

2.2.2-unstable.0

5 years ago

2.2.1-beta

5 years ago

2.2.1-unstable

5 years ago

2.2.1

5 years ago

2.2.0

5 years ago

2.2.0-unstable

5 years ago

2.1.0

5 years ago

2.1.0-unstable.1

5 years ago

2.1.0-unstable.0

5 years ago

2.0.13

5 years ago

2.0.12

5 years ago

2.0.12-unstable

5 years ago

2.0.10

5 years ago

2.0.9

5 years ago

2.0.8

5 years ago

2.0.8-unstable.0

5 years ago

2.0.7

5 years ago

2.0.7-unstable.0

5 years ago

2.0.6

5 years ago

2.0.6-unstable.3

5 years ago

2.0.6-unstable.2

5 years ago

2.0.6-unstable.1

5 years ago

2.0.6-unstable.0

5 years ago

2.0.5

5 years ago

2.0.5-unstable.0

5 years ago

2.0.4

5 years ago

2.0.4-unstable

5 years ago

2.0.3

5 years ago

2.0.2

5 years ago

2.0.2-unstable.0

5 years ago

2.0.1

5 years ago

2.0.0

5 years ago

2.0.0-alpha.2

5 years ago

2.0.0-alpha.1

5 years ago

2.0.0-alpha.0

5 years ago

1.2.0-alpha.2

5 years ago

1.2.0-alpha.1

5 years ago

1.2.0-alpha.0

5 years ago

1.1.5-unstable.0

5 years ago

1.1.4

5 years ago

1.1.4-unstable

5 years ago

1.1.3

5 years ago

1.1.3-unstable

5 years ago

1.1.2

5 years ago

1.1.1

5 years ago

1.1.0

5 years ago

1.0.7

5 years ago

1.0.6

5 years ago

1.0.5

5 years ago

1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0-alpha.7

5 years ago

1.0.0-alpha.6

5 years ago

1.0.0-alpha.5

5 years ago

1.0.0-alpha.4

5 years ago

1.0.0-alpha.3

5 years ago

1.0.0-alpha.2

5 years ago

1.0.0-alpha.1

5 years ago

1.0.0-alpha.0

5 years ago

1.0.0-alpha

5 years ago