Automatically Generated Actions

In the Quick Start, we implemented the simplest counter model, which still required 10 lines of code. In fact, Modern.js supports automatically generating commonly used actions based on the declared state type, which reduces the amount of boilerplate code. The currently supported types are:

  • Primitive data types
  • Array types
  • Simple object types (Plain Object)

Primitive data types

const countModel = model('count').define({ state: 1 });

As shown above, we only need one line to create a simple countModel. Here's an example code that uses the model:

function Counter() {
  const [state, actions] = useModel(countModel);

  useEffect(() => {
    // Add 1
    actions.setState(state + 1);
  }, []);
}

Array Types

When the state is an array type, an example code for automatically generating actions is shown below:

const countModel = model('count').define({ state: [] });

function Counter() {
  const [state, actions] = useModel(countModel);

  useEffect(() => {
    actions.push(1);
    actions.pop();
    actions.shift();
    actions.unshift(1);
    actions.concat([1]);
    actions.splice(0, 1, 2);
    actions.filter(value => value > 1);
  }, []);
}

We can use the methods of the JavaScript Array object to modify the state.

Simple Object Types

When the state is a simple object type, an example code for automatically generating actions is shown below:

const countModel = model('count').define({
  state: {
    a: 1,
    b: [],
    c: {},
  },
});

function Counter() {
  const [state, actions] = useModel(countModel);

  useEffect(() => {
    actions.setA(2);
    actions.setB([1]);
    actions.setC({ a: 1 });
  }, []);
}

Three different fields a, b, and c each generate setA, setB, and setC actions, respectively.

INFO

When the user-defined action and the action automatically generated by Modern.js have the same name, the user-defined action takes precedence. For example, if setA action is already defined in countModel, calling actions.setA() executes the user-defined setA.

Additional Information

For more information on related APIs, please refer to here.