How to use mobx-state-tree - 10 common examples

To help you get started, we’ve selected a few mobx-state-tree examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Feverqwe / tSearch / srcDraft / js / models / optionsModel.js View on Github external
const oneLimit = promiseLimit(1);

const defaultOptions = {
  sortByList: [{by: 'quality'}]
};

const optionModelMap = {
  sortByList: types.frozen,
};

const optionsKeys = Object.keys(defaultOptions);

const optionsModel = types.model('optionsModel', Object.assign({
  state: types.optional(types.string, 'idle'), // idle, loading, ready, error
  options: types.optional(types.model(optionsKeys.reduce((obj, key) => {
    obj[key] = optionModelMap[key];
    return obj;
  }, {})), {}),
})).actions(self => {
  return {
    assign(obj) {
      Object.assign(self, obj);
    },
    set(key, value) {
      self.options[key] = value;
      return self.save();
    },
    get(key) {
      return self.options[key];
    }
  };
github PacktPublishing / MobX-Quick-Start-Guide / src / Chapter08 / mst / references.js View on Github external
export const ReferencesExample = asComponent(() => {
    const User = types.model('User', {
        userid: types.string, // uniquely identifies this User
        name: types.string,
        age: 42,
        twitter: types.maybe(
            types.refinement(types.string, v => /^\w+$/.test(v)),
        ),
    });

    const Todo = types
        .model('Todo', {
            assignee: types.string, // represents a User
            title: types.string,
            done: false,
        })
        .views(self => ({
            getAssignee() {
                if (!this.assignee) return undefined;
                return getRoot(self).users.get(this.assignee);
            },
        }))
github zooniverse / front-end-monorepo / packages / app-project / stores / YourStats.js View on Github external
const query = {
            project_id: project.id,
            user_id: user.id
          }
          // TODO: this should really share the UPP that's being requested by the classifier.
          const response = yield panoptes.get('/project_preferences', query, { authorization })
          const [ preferences ] = response.body.project_preferences
          self.totalCount = preferences ? preferences.activity_count : 0
        } catch (error) {
          console.error(error)
          self.error = error
          self.loadingState = asyncStates.error
        }
      }),

      fetchDailyCounts: flow(function * fetchDailyCounts () {
        const { project, user } = getRoot(self)
        self.loadingState = asyncStates.loading
        let dailyCounts
        try {
          const token = yield auth.checkBearerToken()
          const Authorization = `Bearer ${token}`
          statsClient.setHeaders({
            Authorization
          })
          const query = `{
            statsCount(
              eventType: "classification",
              interval: "1 Day",
              window: "1 Week",
              projectId: "${project.id}",
              userId: "${user.id}"
github baidu / amis / src / store / form.ts View on Github external
} else {
          if (options && options.onSuccess) {
            const ret = options.onSuccess(json);

            if (ret && ret.then) {
              yield ret;
            }
          }
          self.markSaving(false);
          self.updateMessage(json.msg || (options && options.successMessage));
          self.msg &&
            (getRoot(self) as IRendererStore).notify('success', self.msg);
          return json.data;
        }
      } catch (e) {
        if ((getRoot(self) as IRendererStore).storeType !== 'RendererStore') {
          // 已经销毁了,不管这些数据了。
          return;
        }

        self.markSaving(false);
        // console.error(e.stack);`
        (getRoot(self) as IRendererStore).notify('error', e.message);
        throw e;
      }
    });
github fadiquader / next.js-mst / stores / index.js View on Github external
// fetch: fetcher,
        alert: m => console.log(m) // Noop for demo: window.alert(m)
      }
    )
  }
  if(store === null) {
    store = Store.create(
      {},
      {
        // fetch: fetcher,
        alert: m => console.log(m) // Noop for demo: window.alert(m)
      }
    )
  }
  if (snapshot) {
    applySnapshot(store, snapshot)
  }
  return store
}
github fluid-notion / fluid-outliner / core / utils / mobx-helpers.ts View on Github external
export const safeApplySnapshot = (target: IStateTreeNode, snapshot: any) => {
    try {
        applySnapshot(target, snapshot)
        return true
    } catch (e) {
        // tslint:disable-next-line:no-console
        console.error(e)
        alert(
            "Saved outline was found to be corrupt." +
                "Please report this as an issue." +
                "It will help us debug if you could also attach the downloaded snapshot in the bug report"
        )
        try {
            downloadJSON(snapshot)
        } catch (e) {
            // tslint:disable-next-line:no-console
            console.error(e)
            alert("Failed to download snapshot")
        }
github coderplanets / coderplanets_web / containers / UpgradePackges / store.js View on Github external
/*
 * UpgradePackges store
 *
 */

import { types as t, getParent } from 'mobx-state-tree'
// import R from 'ramda'

import { markStates, buildLog } from '@utils'

/* eslint-disable-next-line */
const log = buildLog('S:UpgradePackges')

const UpgradePackges = t
  .model('UpgradePackges', {
    show: t.optional(t.boolean, false),
  })
  .views(self => ({
    get isLogin() {
      return self.root.account.isLogin
    },
    get root() {
      return getParent(self)
    },
  }))
  .actions(self => ({
    authWarning(options) {
      self.root.authWarning(options)
    },
    cashierHelper(opt) {
      self.root.cashierHelper(opt)
    },
github coderplanets / coderplanets_web / src / stores / RootStore / index.js View on Github external
.model({
    // domain stores
    account: t.optional(AccountStore, {}),
    route: t.optional(RouteStore, {}),
    viewing: t.optional(ViewingStore, {}),
    comments: t.optional(CommentsStore, {}),
    theme: t.optional(ThemeStore, ThemeDefaults),
    appLocale: t.optional(t.enumeration('locale', ['zh', 'en']), 'zh'),
    appLangs: t.map(t.frozen),
    // domain end

    // toolbox
    sidebar: t.optional(SidebarStore, { menuItems: [] }),
    preview: t.optional(PreviewStore, { visible: false }),
    doraemon: t.optional(DoraemonStore, {}),
    jobEditor: t.optional(JobEditorStore, {}),
    postEditor: t.optional(PostEditorStore, {}),
    videoEditor: t.optional(VideoEditorStore, {}),
    repoEditor: t.optional(RepoEditorStore, {}),
    accountEditor: t.optional(AccountEditorStore, {}),
    upgradePackges: t.optional(UpgradePackgesStore, {}),
    mailBox: t.optional(MailBoxStore, {}),
    labeler: t.optional(LabelerStore, {}),
    docUploader: t.optional(DocUploaderStore, {}),
    avatarAdder: t.optional(AvatarAdderStore, {}),
    // toolbox end

    // layouts > xxx > papers
    // layouts
    globalLayout: t.optional(GlobalLayoutStore, {}),
    header: t.optional(HeaderStore, {}),
    content: t.optional(ContentStore, {}),
github coderplanets / coderplanets_web / stores / CommunitiesStore / index.js View on Github external
// import PlModel from './PlModel'

// import FrameworkModel from './FrameworkModel'
// / import DatabaseModel from './DatabaseModel'
// import CheatSheetModal from './CheatSheetModal'

/* eslint-disable no-unused-vars */
const debug = makeDebugger('S:communities')
/* eslint-enable no-unused-vars */
// const debug = makeDebugger('S:CommunitiesStore')

const CommunitiesStore = t
  .model('CommunitiesStore', {
    entries: t.optional(t.array(Community), []),
    pageNumber: t.optional(t.number, 1),
    pageSize: t.optional(t.number, 20), // TODO: USE CONSTANTS
    totalCount: t.optional(t.number, 0),
    totalPages: t.optional(t.number, 0),

    // filter: {catalogry ... }

    // id: t.identifier(),
    // languages: t.map(PlModel),
    // frameworks: t.map(FrameworkModel),
    // databases: t.map(DatabaseModel),
    // cheatsheet: t.optional(CheatSheetModal, { title: '', desc: '', raw: '' }),
    // jobs: ...
    // themes: ...
    // debug: ...
    // user: ...
    // cmds: t.map(CmdModel),
github coderplanets / coderplanets_web / src / stores / SharedModel / Comment.js View on Github external
author: t.optional(User, {}),
})

const CommentBase = {
  id: t.maybeNull(t.string),
  body: t.maybeNull(t.string),
  author: t.optional(User, {}),
  floor: t.number,
  replyTo: t.maybeNull(CommentBrief),
  replies: t.optional(t.array(CommentBrief), []),
  repliesCount: t.optional(t.number, 0),
  likesCount: t.optional(t.number, 0),
  dislikesCount: t.optional(t.number, 0),
  viewerHasLiked: t.maybeNull(t.boolean),
  viewerHasDisliked: t.maybeNull(t.boolean),
  insertedAt: t.optional(t.string, ''),
  updatedAt: t.optional(t.string, ''),
}

export const Comment = t.model('Comment', {
  ...CommentBase,
})

export const PagedComments = t.model('PagedComments', {
  entries: t.optional(t.array(Comment), []),
  pageNumber: t.optional(t.number, 1),
  pageSize: t.optional(t.number, PAGE_SIZE.D),
  totalCount: t.optional(t.number, 0),
  totalPages: t.optional(t.number, 0),
})

// paged post comemnts