Mobx-state-tree: Tons of setters boilerplate

Created on 29 Apr 2019  路  6Comments  路  Source: mobxjs/mobx-state-tree

I need a way to create / update tens of entities, where each of them has tens of fields. Usually, there's a single dialog for both actions using a MST model. I don't mind adding the fields to the model, but adding also the setters feels too repetitive.

So I did something like

.actions(self => ({
    applyEvent(event: SyntheticEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) {
        const t = event.target as any
        if (t instanceof HTMLInputElement && t.type==='checkbox') {
            self[t.name] = !self[t.name]
        } else {
            self[t.name] = t.value
        }
    },
}))

which allows me to simply write

<TextField className={classes.input} required
    name='promocode'
    value={store.promocode}
    onChange={store.applyEvent}
/>

which works, but feels like a terrible hack. Unfortunately, the saner alternatives are either too verbose (adding a setter per field or an arrow function to the dialog) or inefficient (arrow function in onChange).

My questions are:

  • Is something wrong with my approach (apart from event.target==null, which I can live with)?
  • Is there a better way?
question stale

All 6 comments

What about an action that gets the prop name as first parm, and value of the second?
You can also make it play with typescript using keyof and typeof

// actions(self ...
set<K extends keyof typeof self>(key: K, value: SnapshotOrInstance<typeof self[K]>): void {
  self[key] = value
}

didn't try it, but should be something like that

Doesn't it imply needing an arrow function in onChange (causing needless re-rendering) or needing some bridge-function per field (more boilerplate)?

<K extends keyof typeof self>

Sounds funny, typescript is cool.

TypeScript, and react best practices requires some strictness and not using some very dynamic language features.

You may always use "run in action" and directly set what ever you like to what you like in

.actions(self => ({
   runInAction(fn) {
      return fn()
   }
}))

https://github.com/mobxjs/mobx-state-tree/issues/915#issuecomment-404461322

This issue has been automatically marked as stale because it has not had recent activity in the last 10 days. It will be closed in 4 days if no further activity occurs. Thank you for your contributions.

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs or questions.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ShootingStarr picture ShootingStarr  路  4Comments

terrysahaidak picture terrysahaidak  路  3Comments

EricForgy picture EricForgy  路  4Comments

mreed picture mreed  路  3Comments

A-gambit picture A-gambit  路  3Comments