Typesafe Vuex with Kotlin JS

If you don’t know what Vuex is or what it is useful for, please refer to its website.

First, define some state. In this example, we create a simple class with just one integer.

class CartState {
    var count: Int = 0
}

Second, create a Vuex module. It’s not necessary to create a module, but it’s useful for large projects and better to use it earlier than to refactor more code in the future.

To benefit from Kotlin’s data class syntax, you can create simple abstract model for Vuex modules:

open class VuexModule(
        val namespaced: Boolean = true,
        val state: Any,
        val mutations: Any? = null,
        val actions: Any? = null,
        val getters: Any? = null
)

And it’s easy to use it:

class CartModule : VuexModule(

        state = CartState(),

        mutations = object {
            val increment: (state: CartState) -> Unit = { state ->
                state.count++
            }
        }

)

To be able to access states in a typesafe way, we need an enclosing class for them. There are some other states for illustration purposes :-).


class States {
    val cart = CartState()
    val common = CommonState()
    val another = AnotherState()
}

We are almost done! The last step is to create an external class for Vuex and its instance:


external class Vuex {
    class Store(store: Any) {
        val state: States = definedExternally
        fun commit(name: String, vararg params: Any)
    }
}

val store = Vuex.Store(object {
    val modules = object {
        val cart = CartModule()
        val common = CommonModule()
    }
})

From this moment, global store.state.cart.count is available. To commit change, it’s easy to call store.commit(“cart/increment”).

Leave a Reply

Your email address will not be published. Required fields are marked *