How to use the mobx-state-tree.types.maybe function in mobx-state-tree

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 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 coderplanets / coderplanets_admin / stores / CommunitiesContentStore / index.js View on Github external
} from '../SharedModel'
import { markStates, makeDebugger, stripMobx } from '../../utils'
/* eslint-disable no-unused-vars */
const debug = makeDebugger('S:CommunitiesContentStore')
/* eslint-enable no-unused-vars */

const CommunitiesContentStore = t
  .model('CommunitiesContentStore', {
    // all the communities
    pagedCommunities: t.maybe(PagedCommunities),
    pagedCategories: t.maybe(PagedCategories),
    pagedTags: t.maybe(PagedTags),
    pagedThreads: t.maybe(PagedThreads),

    pagedPosts: t.maybe(PagedPosts),
    pagedJobs: t.maybe(PagedJobs),

    communitiesLoading: t.optional(t.boolean, false),
    tagsLoading: t.optional(t.boolean, false),
    categoriesLoading: t.optional(t.boolean, false),
    postsLoading: t.optional(t.boolean, false),
    jobsLoading: t.optional(t.boolean, false),
  })
  .views(self => ({
    get root() {
      return getParent(self)
    },
    get isLogin() {
      return self.root.account.isLogin
    },
    get curRoute() {
      return self.root.curRoute
github bailabs / tailpos / src / store / PosStore / ReceiptStore.js View on Github external
self.syncStatus = true;
    },
    setCancel(reason) {
      self.reason = reason;
      self.status = "cancelled";
      self.dateUpdated = Date.now();
      self.syncStatus = false;
    },
  }));

const Store = types
  .model("ReceiptStore", {
    rows: types.optional(types.array(types.reference(Receipt)), []),
    defaultCustomer: types.optional(types.reference(Customer), ""),
    defaultReceipt: types.maybe(types.reference(Receipt)),
    previousReceipt: types.maybe(types.reference(Receipt)),
    selectedLine: types.maybe(types.reference(ReceiptLine)),
    lastScannedBarcode: types.optional(types.string, ""),
    commissions: types.optional(types.string, "[]"),
  })
  .actions(self => ({
    initSync(session) {
      replicationHandler = syncDB(db, "receipts", session);
      replicationHandler.on("complete", function() {
        if (self.rows.length === 0) {
          // self.getFromDb(20);
        }
      });
    },
    destroyDb() {
      self.defaultCustomer = "";
      self.defaultReceipt = null;
github alexvcasillas / react-mobx-state-tree / src / stores / github.js View on Github external
name: types.string,
    description: types.maybe(types.string),
    url: types.maybe(types.string),
    homepageUrl: types.maybe(types.string),
    isFork: types.maybe(types.boolean),
    stargazers: types.optional(types.frozen, null),
    createdAt: types.maybe(types.string),
    updatedAt: types.maybe(types.string)
  })
  .views(self => ({}))
  .actions(self => ({}));

const GithubStore = types
  .model('GithubStore', {
    searchName: types.optional(types.string, ''),
    user: types.optional(types.maybe(UserModel), null), // Object with all the user data that comes from the Github API Fetch
    repos: types.optional(types.array(RepositoryModel), []), // Array of Repositories that comes from the Github API Fetch
    fetchingData: types.optional(types.boolean, false)
  })
  .views(self => ({
    get AmountOfRepos() {
      return this.repos.length;
    }
  }))
  .actions(self => {
    const fetchFromGithub = flow(function* () {
      self.fetchingData = true;
      const { data: { viewer } } = yield client.query({
        query: viewerQuery,
        fetchPolicy: 'network-only'
      });
      self.user = UserModel.create({
github charlessolar / eShopOnContainersDDD / src / Web / src / app / parts / basket / stores / paymentMethodForm.ts View on Github external
alias: string;
  cardNumber: string;
  securityNumber: string;
  cardholderName: string;
  expiration: string;
  cardType: string;

  readonly form: { [idx: string]: FieldDefinition };
  submit: () => Promise<{}>;
}
export const PaymentMethodFormModel = types
  .model({
    id: types.optional(types.identifier(types.string), uuid),
    alias: types.maybe(types.string),
    cardNumber: types.maybe(types.string),
    securityNumber: types.maybe(types.string),
    cardholderName: types.maybe(types.string),
    expiration: types.maybe(types.string),
    cardType: types.maybe(types.string)
  })
  .views(self => ({
    get validation() {
      const validation = {
        alias: rules.paymentMethodForm.alias,
        cardNumber: rules.paymentMethodForm.cardNumber,
        securityNumber: rules.paymentMethodForm.securityNumber,
        cardholderName: rules.paymentMethodForm.cardholderName,
        expiration: rules.paymentMethodForm.expiration,
        cardType: rules.paymentMethodForm.cardType
      };

      return validate(self, validation);
github alexvcasillas / react-mobx-state-tree / src / stores / github.js View on Github external
const aUpdated = new Date(a.updatedAt);
  const bUpdated = new Date(b.updatedAt);
  if (aUpdated > bUpdated) {
    return -1;
  }
  if (aUpdated < bUpdated) {
    return 1;
  }
  return 0;
}

const UserModel = types
  .model('UserModel', {
    name: types.maybe(types.string),
    bio: types.maybe(types.string),
    avatar: types.maybe(types.string),
    followers: types.maybe(types.number),
    following: types.maybe(types.number)
  })
  .views(self => ({}))
  .actions(self => ({}));

const RepositoryModel = types
  .model('RepoModel', {
    name: types.string,
    description: types.maybe(types.string),
    url: types.maybe(types.string),
    homepageUrl: types.maybe(types.string),
    isFork: types.maybe(types.boolean),
    stargazers: types.optional(types.frozen, null),
    createdAt: types.maybe(types.string),
    updatedAt: types.maybe(types.string)
github grafana / grafana / public / app / stores / PermissionsStore / PermissionsStoreItem.ts View on Github external
import { types } from 'mobx-state-tree';

export const PermissionsStoreItem = types
  .model('PermissionsStoreItem', {
    dashboardId: types.optional(types.number, -1),
    permission: types.number,
    permissionName: types.maybe(types.string),
    role: types.maybe(types.string),
    team: types.optional(types.string, ''),
    teamId: types.optional(types.number, 0),
    userEmail: types.optional(types.string, ''),
    userId: types.optional(types.number, 0),
    userLogin: types.optional(types.string, ''),
    inherited: types.maybe(types.boolean),
    sortRank: types.maybe(types.number),
    icon: types.maybe(types.string),
    nameHtml: types.maybe(types.string),
    sortName: types.maybe(types.string),
  })
  .actions(self => ({
    updateRole: role => {
      self.role = role;
    },
    updatePermission(permission: number, permissionName: string) {
      self.permission = permission;
      self.permissionName = permissionName;
    },
  }));
github naguvan / react-mst-form / packages / react-mst-form / src / models / Type / Value / Value.ts View on Github external
type: types.literal(type),
      value: types.optional(kind, defaultv),
      default: types.optional(kind, defaultv),
      initial: types.optional(kind, defaultv),
      enum: types.maybe(types.array(kind)),
      options: types.maybe(
        types.array(types.model({ label: types.string, value: kind }))
      ),
      const: types.maybe(kind),
      name: types.optional(types.string, ""),
      mandatory: types.optional(types.boolean, false),
      disabled: types.optional(types.boolean, false),
      visible: types.optional(types.boolean, true),
      errors: types.optional(types.array(types.string), []),
      component: types.maybe(types.string),
      sequence: types.maybe(types.number)
    })
    .volatile(it => ({ _validating: false, syncing: false }))
    .actions(it => ({
      afterCreate() {
        if (it.name === "" && it.title) {
          const { title } = it;
          it.name = title.toLowerCase().replace(" ", "-");
        }
        it.initial = it.value;
        if (
          it.enum != null &&
          it.enum.length > 0 &&
          (it.options == null || it.options.length === 0)
        ) {
          const options = it.enum.map(option => ({
            label: String(option),
github Feverqwe / tSearch / src / stores / TrackerStoreStore.js View on Github external
* @property {TrackerMetaStore|undefined} meta
 * @property {string|undefined} code
 * @property {function:Promise} fetch
 * @property {function} save
 * @property {*} tracker
 * @property {*} hasTracker
 * @property {function} deleteTacker
 */
const TrackerStoreResultStore = types.model('TrackerStoreResultStore', {
  state: types.optional(types.enumeration(['idle', 'pending', 'done', 'error']), 'idle'),
  name: types.string,
  size: types.number,
  fileType: types.enumeration(['js', 'json']),
  html_url: types.string,
  download_url: types.string,
  meta: types.maybe(TrackerMetaStore),
  code: types.maybe(types.string),
}).actions((self) => {
  return {
    fetch: flow(function* () {
      if (self.state === 'pending') return;
      const {download_url: url, html_url, fileType} = self;
      self.state = 'pending';
      try {
        let code = yield fetch(url).then(async (response) => {
          if (!response.ok) {
            throw new Error('Response is not ok');
          }

          const text = await response.text();
          if (fileType === 'json') {
            const jsonCodeToUserscript = (await import("../tools/jsonCodeToUserscript")).default;
github Feverqwe / tSearch / src / stores / ExplorerStore.js View on Github external
* @property {string} id
 */
const ExplorerSectionStore = types.model('ExplorerSectionStore', {
  id: types.identifier,
});


/**
 * @typedef {{}} ExplorerStore
 * @property {string} [state]
 * @property {ExplorerSectionStore[]|undefined} sections
 * @property {function} fetchSections
 */
const ExplorerStore = types.model('ExplorerStore', {
  state: types.optional(types.enumeration(['idle', 'pending', 'done', 'error']), 'idle'),
  sections: types.maybe(types.array(ExplorerSectionStore)),
}).actions(self => {
  return {
    fetchSections: flow(function* () {
      self.state = 'pending';
      try {

        if (isAlive(self)) {
          self.state = 'done';
        }
      } catch (err) {
        logger.error('fetchSections error', err);
        if (isAlive(self)) {
          self.state = 'error';
        }
      }
    }),