How to use the mobx-state-tree.types.reference 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 birkir / hekla / src / stores / Account.ts View on Github external
import * as Keychain from 'react-native-keychain';
import Hackernews, { API_URL, LOGIN_INCORRECT, LOGIN_ERROR, LOGIN_EXISTS } from './services/Hackernews';
import User from './models/User';
import Users from './Users';

const Account = types
  .model('Account', {
    isLoggedIn: types.optional(types.boolean, false),
    isLoading: types.optional(types.boolean, false),
    isChecking: types.optional(types.boolean, true),
    voted: types.optional(types.map(types.boolean), {}),
    favorited: types.optional(types.map(types.boolean), {}),
    flagged: types.optional(types.map(types.boolean), {}),
    hidden: types.optional(types.map(types.boolean), {}),
    read: types.optional(types.map(types.boolean), {}),
    user: types.maybe(types.reference(User)),
  })
  .views(self => ({
    get userId() {
      return self.user && self.user.id;
    },
  }))
  .actions((self) => {

    const populate = flow(function* () {
      // Mark every item in list
      const add = (where, items) => items.forEach(({ id }) => where.set(id, true));

      // Sync last 30 voted stories
      add(self.voted, yield Hackernews.voted('submissions', self.user.id, 1));

      // Sync last 90 voted comments
github bailabs / tailpos / src / store / PosStore / ReceiptStore.js View on Github external
},
    changeStatus() {
      // self.dateUpdate = Date.now;
      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);
        }
      });
    },
github coderplanets / coderplanets_web / stores / CartStore / index.js View on Github external
import { when, reaction } from 'mobx'
/* import { types, getParent, getSnapshot, applySnapshot } from 'mobx-state-tree' */
import { types, getParent, getSnapshot } from 'mobx-state-tree'
import { Book } from '../BookStore'
import { makeDebugger } from '../../utils/functions'

const debug = makeDebugger('store:CartStore')

export const CartEntry = types
  .model('CartEntry', {
    quantity: 0,
    book: types.reference(Book),
  })
  .views(self => ({
    get price() {
      return self.book.price * self.quantity
    },
    get isValidBook() {
      return self.book.isAvailable
    },
  }))
  .actions(self => ({
    increaseQuantity(amount) {
      self.quantity += amount
    },
    setQuantity(amount) {
      self.quantity = amount
    },
github bailabs / tailpos / src / store / PosStore / PaymentStore.js View on Github external
postProcessSnapshot(snapshot) {
      saveSnapshotToDB(db, snapshot);
    },
    setDeviceId(id) {
      self.deviceId = id;
    },
    edit(data) {
      editFields(self, data);
    },
  }));

const PaymentStore = types
  .model("PaymentStore", {
    rows: types.optional(types.array(Payment), []),
    defaultPayment: types.maybe(types.reference(Payment)),
    paymentReceipt: types.maybe(types.reference(Receipt)),
    paymentCustomer: types.maybe(types.reference(Customer)),
  })
  .views(self => ({
    get amountChange() {
      const netTotal = self.paymentReceipt.netTotal;
      const paid = self.defaultPayment.paid;
      return paid - netTotal;
    },
  }))
  .actions(self => ({
    initSync(session) {
      syncDB(db, "payments", session, () => {
        if (self.rows.length === 0) {
          self.getFromDb(20);
        }
      });
github zooniverse / front-end-monorepo / packages / lib-auth / src / models / oauth / UserStore.js View on Github external
import { flow, getRoot, types } from 'mobx-state-tree'
import asyncStates from '@zooniverse/async-states'
import { panoptes } from '@zooniverse/panoptes-js'

import UserResource from './UserResource'

const UserStore = types
  .model('UserStore', {
    active: types.maybe(types.reference(UserResource)),
    loadingState: types.optional(types.enumeration('loadingState', asyncStates.values), asyncStates.initialized),
    resources: types.map(UserResource),
    type: types.optional(types.string, 'users')
  })

  .actions(self => {
    function * fetchResource (token) {
      console.log('Getting user')

      if (token) {
        const { type } = self
        self.loadingState = asyncStates.loading
        try {
          const response = yield panoptes.get('/me', {}, `Bearer ${token}`)
          const user = response.body[type][0]
github heartexlabs / label-studio / src / stores / CompletionStore.js View on Github external
createdDate: types.optional(types.string, Utils.UDate.currentISODate()),
    createdAgo: types.maybeNull(types.string),
    createdBy: types.optional(types.string, "Admin"),

    loadedDate: types.optional(types.Date, new Date()),
    leadTime: types.maybeNull(types.number),

    userGenerate: types.optional(types.boolean, true),
    update: types.optional(types.boolean, false),
    sentUserGenerate: types.optional(types.boolean, false),
    localUpdate: types.optional(types.boolean, false),

    honeypot: types.optional(types.boolean, false),

    root: Types.allModelsTypes(),
    names: types.map(types.reference(Types.allModelsTypes())),
    toNames: types.map(types.array(types.reference(Types.allModelsTypes()))),

    history: types.optional(TimeTraveller, { targetPath: "../root" }),

    dragMode: types.optional(types.boolean, false),

    edittable: types.optional(types.boolean, true),

    relationMode: types.optional(types.boolean, false),
    relationStore: types.optional(RelationStore, {
      relations: [],
    }),

    normalizationMode: types.optional(types.boolean, false),
    normalizationStore: types.optional(NormalizationStore, {
      normalizations: [],
github bailabs / tailpos / src / store / PosStore / ItemStore.js View on Github external
setFavorite() {
      self.favorite = "true";
    },
    setUnfavorite() {
      self.favorite = "false";
    },
  }));
//Favorites
const Store = types
  .model("ItemStore", {
    filtered: types.optional(types.boolean, false),
    rows: types.optional(types.array(Item), []),
    favoriteRows: types.optional(types.array(Item), []),
    queriedRows: types.optional(types.array(Item), []),
    categoryLengths: types.optional(types.string, "[]"),
    selectedItem: types.maybe(types.reference(Item)),
    duplicateBarcodeObject: types.optional(types.string, ""),
    barcodeValue: types.optional(types.string, ""),
    itemsLength: types.optional(types.number, 0),
    favoritesLength: types.optional(types.number, 0),
    itemsToBeSynced: types.optional(types.array(Item), []),
  })
  .actions(self => ({
    initSync(session) {
      replicationHandler = syncDB(db, "items", session);
      replicationHandler.on("complete", function() {
        if (self.rows.length === 0) {
          self.getFromDb(20);
        }
      });
    },
    destroyDb() {
github birkir / hekla / src / stores / models / Item.ts View on Github external
} catch (err) {
          comment.setIsError(true);
        }
      })();

      return comment;
    })();
  },
}));

/**
 * Getter and setter for item references
 * @param {string} identifier item.id
 * @return {Item}
 */
export const ItemReference = types.reference(Item, {
  get(identifier: string, parent: any) {
    return Items.items.get(identifier) || null;
  },
  set(value: any) {
    return value;
  },
});

export default Item;
github birkir / kvikmyndr-app / src / store / cinemas.ts View on Github external
import { types, flow } from 'mobx-state-tree';
import { client } from '../services/graphql.service';
import { Cinema } from './models/Cinema';
import fetchCinemaByIdQuery from '../queries/fetchCinemaById.gql';
import fetchAllCinemas from '../queries/fetchAllCinemas.gql';

export const CinemaReference = types.reference(Cinema, {
  get(identifier: string) {
    return Cinemas.getOrLoadById(identifier) as typeof Cinema.Type || [];
  },
  set(value: typeof Cinema.Type) {
    return value.id;
  },
});

export const Cinemas = types.model('Cinemas', {
  cinemas: types.map(Cinema),
})
.actions((self) => {

  const addCinema = (obj: any) => {
    const cinema = { ...obj };
    if (self.cinemas.has(cinema.id)) {
github Temzasse / yak-chat / client / src / channel / channel.model.js View on Github external
import { types } from 'mobx-state-tree';
import User from '../user/user.model';
import { guid } from '../services/utils';

const Message = types.model({
  id: types.identifier(types.string, () => guid()),
  content: '',
  type: types.optional(types.string, 'message'),
  timestamp: types.optional(types.string, () => {
    return new Date().toISOString();
  }),
  sender: types.reference(User)
});

const Channel = types
  .model({
    id: types.identifier(types.string),
    loadingMessages: false,
    unseenMessages: false,
    followingMessages: false,
    messages: types.optional(types.array(Message), []),
    userCount: types.optional(types.number, 0),
  })
  .actions(self => ({
    followMessages() {
      self.followingMessages = true;
      self.unseenMessages = false;
    },