Kashuab / mobx-depot

Scaffold MobX-powered models, queries and mutations with your GraphQL schema.
https://mobx-depot.dev
MIT License
8 stars 0 forks source link

Castable #47

Closed KashubaK closed 1 year ago

KashubaK commented 1 year ago

See #45

This is an alternative implementation of model casting, that is less verbose and more convenient.

// UserModel has firstName, lastName, email, etc.
import { UserModel } from '~models/depot';
import { castable } from 'mobx-depot';

export const EditableUser = castable(UserModel, {
  editing: false,
  setFirstName(firstName: string) {
    this.firstName = firstName;
  },
  setEditing(editing: boolean) {
    this.editing = editing;
    // Note: `this` is both the UserModel instance, as well as any new methods/props we're adding here
  }
});

const user = new UserModel({ firstName: 'Jim' });
const editableUser = EditableUser(user);

editableUser.firstName; // -> 'Jim'
editableUser.setFirstName('Bob');

editableUser.firstName; // -> 'Bob'
user.firstName; // -> 'Jim'

Much of the resulting behavior is the same, with a few differences:

TODO:

It would be nice if castable could be generic, i.e:

const Genericable = castable({
  independentState: 0,
  shoot() {
    this.independentState++;
  }
});

In this case, Genericable could be applied to any model since it doesn't depend on the model's state.

Kashuab commented 1 year ago

We need a better word to describe the behavior here. You're kind of casting, but in regards to memoizing by instance/wrapper class combo it is not clear.

KashubaK commented 1 year ago

Closed in favor of #48