Search code examples
react-nativemobxmobx-reactmobx-state-tree

mobx-state-tree does not update the model with react-native


I try to create a User model with react-native, mobx, mobx-state-tree

My User Model:

const UserProfileModel = types.model("UserProfile").props({
  description: types.maybeNull(types.string),
})

/**
 * Model description here for TypeScript hints.
 */
export const UserModel = types
  .model("User")
  .props({
    created_at: types.optional(types.string, ""),
    email: types.optional(types.string, ""),
    first_name: types.optional(types.string, ""),
    id: types.optional(types.string, ""),
    last_name: types.optional(types.string, ""),
    nick_name: types.maybeNull(types.string),
    updated_at: types.optional(types.string, ""),
    // @ts-ignore
    profile: types.optional(UserProfileModel, {}),
  })
  .actions((self: any)  => ({
    updateNickName(nick_name: string): void {
      self.nick_name = nick_name
    }
  }))

And the class who call the updateNickName action:

@inject("userModel")
@observer
export class EditMyProfileScreen extends React.Component {

  @observable private readonly userProfile: IUser = {} as IUser

  constructor(props) {
    super(props)
    this.userProfile = clone(props.userModel)
  }

  @autobind
  private async sendUpdateToServer(): Promise<void> {
    const { userModel } = this.props
    // do some async request to the server
    userModel.updateNickName(this.userProfile.nick_name)
    console.log(userModel) // this console.log print an old version of the javascript object
  }

  render() {
    // do stuff
  }
}

But the user seems to be not updated after userModel.updateNickName was called.

Why the nick_name field is not updated?


Solution

  • After upgrading mobx-state-tree to v3.15.0 the issue seems to be fixed.