Skip to content

Get Started

Simple Counter example with Reapex.

Installation

Installing Reapex and peer dependencies. If you add Reapex to an existing React application, you may already have all of them in your existing application.

yarn add reapexyarn add react react-dom redux react-redux redux-saga

Create a Model

A model is simply a slice of redux global state, the initial value of a model can be a plain object or an Immutable Record.


import { App } from 'reapex'

export const app = new App()
const CounterModel = app.model('Counter', { total: 50 })

// or with Immuable Record
import { Record } from 'immtable'

const CounterState = Record({ total: 50 })
const CounterModel = app.model('Counter', new CounterState())

Create Mutations

The mutations define operations of how the model data will be updated.

The mutations function accepts an object as the first parameter which keys indicate the operations and the values are function which describe the mutation input and output. This is similar to the reducer function.


const [mutations] = CounterModel.mutations({
  increase: () => state => ({...state, total: state.total + 1}),
  decrease: () => state => ({...state, total: state.total - 1}),
})

// or with Immutable Record
const [mutations] = CounterModel.mutations({
  increase: () => state => state.set('total', state.total + 1),
  decrease: () => state => state.set('total', state.total - 1),
})

Note: typescript will infer the type of initialState and create the a strong-typed state object out of it. In this case, the state we used here will be either {total: number} or Record<{total: number}>.

The return value of mutations funtion is a tuple: [actionCreators, actionTypes], the first value is a map action creators. The second value is a map action types.

With Reapex, there will be no Redux boilerplates of action creators and action types. Reapex generates strong-typed actions creators and action types out of the box.

Connect with Component

After defining the model and mutations, the next step is to connect the component with selectors and mutations. Which is a typical redux container:


export const Counter: React.FC = () => {
  const total = useSelector(CounterModel.selectors.total)
  const dispatch = useDispatch()
  return (
    <>
      <button onClick={() => dispatch(mutations.decrease())}>-</button>
      {total}
      <button onClick={() => dispatch(mutations.increase(1))}>+</button>
    </>
  )
}

Checkout the example

Run and edit the live example at codesandbox.io.

Want to learn more?

Check out the Reapex documentation and learn all about the API.