Manage State using Factory Functions

by kevinfiol

Level: intermediate • Mithril.js Version: latest

In Mithril.js you are free to structure your state data however you'd like, and Mithril.js takes care of the rest. Credits for porsager and foxdonut.

Live Example

Dependencies

Type Name URL
scriptmithril@latesthttps://unpkg.com/mithril@latest

JavaScript

const State = () => ({ count: 0 });

const Actions = state => ({
  increment: () => state.count += 1,
  decrement: () => state.count -= 1
});

const state   = State();
const actions = Actions(state);

const Counter = {
  view: ({ attrs: { state, actions } }) =>
    m('div',
      m('h1', 'Counter'),
      m('p', state.count),
      m('button', { onclick: actions.increment }, '+'),
      m('button', { onclick: actions.decrement }, '-')
    )
};

m.mount(document.body, {
  view: () => m(Counter, { state, actions })
});

The snippet requires the latest version of Mithril.js framework. You should be familiar with most aspects of the framework. So the example is aimed at advanced users.

In this example we can see an example of Mithril.js' m.mount API method, besides it core m() hyperscript function.

The code sample was authored by kevinfiol. It was last modified on 19 October 2021. Want to see more examples written by kevinfiol? Then Click here.

Contribute

Do you see some improvements, that could be addressed here? Then let me know by opening an issue. As an alternative, you can fork the repository on GitHub, push your commits and send a pull request. To start your work, click on the edit link below. Thank you for contributing to this repo.

See more code examples  •  Edit this example on GitHub