How to use the mobx-state-tree.types.map 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 mobxjs / mst-gql / examples / 5-nextjs / src / models / RootStore.base.ts View on Github external
/* The TypeScript type that explicits the refs to other models in order to prevent a circular refs issue */
type Refs = {
  todos: ObservableMap,
  users: ObservableMap
}

/**
* Store, managing, among others, all the objects received through graphQL
*/
export const RootStoreBase = withTypedRefs()(MSTGQLStore
  .named("RootStore")
  .extend(configureStoreMixin([['Todo', () => TodoModel], ['User', () => UserModel]], ['Todo', 'User']))
  .props({
    todos: types.optional(types.map(types.late((): any => TodoModel)), {}),
    users: types.optional(types.map(types.late((): any => UserModel)), {})
  })
  .actions(self => ({
    queryTodos(variables?: {  }, resultSelector: string | ((qb: TodoModelSelector) => TodoModelSelector) = todoModelPrimitives.toString(), options: QueryOptions = {}) {
      return self.query<{ todos: TodoModelType[]}>(`query todos { todos {
        ${typeof resultSelector === "function" ? resultSelector(new TodoModelSelector()).toString() : resultSelector}
      } }`, variables, options)
    },
    queryDoneTodos(variables?: {  }, resultSelector: string | ((qb: TodoModelSelector) => TodoModelSelector) = todoModelPrimitives.toString(), options: QueryOptions = {}) {
      return self.query<{ doneTodos: TodoModelType[]}>(`query doneTodos { doneTodos {
        ${typeof resultSelector === "function" ? resultSelector(new TodoModelSelector()).toString() : resultSelector}
      } }`, variables, options)
    },
    queryUser(variables: { id: string }, resultSelector: string | ((qb: UserModelSelector) => UserModelSelector) = userModelPrimitives.toString(), options: QueryOptions = {}) {
      return self.query<{ user: UserModelType}>(`query user($id: ID!) { user(id: $id) {
        ${typeof resultSelector === "function" ? resultSelector(new UserModelSelector()).toString() : resultSelector}
github knoopx / crypto-watch / src / stores / app-store.js View on Github external
const Filter = types.model({
  query: types.string,
  market: types.string,
})

export const AppStore = types.model({
  isConnected: false,
  muteNotifications: false,
  filter: types.optional(Filter, {
    query: '',
    market: '',
  }),
  watchList: types.optional(types.map(WatchListItem), {}),
  // holdings: types.array(Holding),
  availableExchanges: types.optional(types.array(types.string), []),
  exchanges: types.optional(types.map(Exchange), {}),

  get pairs() {
    return R.flatten(this.exchanges.values().map(e => e.pairs.values()))
  },
},
  {
    addWatchListItem(item) {
      this.watchList.put(item)
    },
    afterCreate() {
      this.tracker = new Tracker(this)
    },

    onConnect() {
      this.isConnected = true
      this.fetchExchanges()
github zooniverse / front-end-monorepo / packages / lib-classifier / src / plugins / drawingTools / models / tools / LineTool / LineTool.js View on Github external
import { types } from 'mobx-state-tree'
import Tool from '../Tool'
import { Line } from '../../marks'

const LineTool = types.model('Line', {
  marks: types.map(Line),
  type: types.literal('line')
})
  .actions(self => {
    function createMark (mark) {
      const newMark = Line.create(mark)
      self.marks.put(newMark)
      return newMark
    }

    return {
      createMark
    }
  })

export default types.compose('LineTool', Tool, LineTool)
github birkir / hekla / src / stores / Items.ts View on Github external
import { flow, types } from 'mobx-state-tree';
import { db } from 'utils/firebase';
import fetchMetadata, { fetchMetadataCache } from 'utils/fetchMetadata';
import Item from './models/Item';

const Items = types
  .model('Items', {
    items: types.map(types.late(() => Item)),
  })
  .actions((self) => {
    return {
      addItem(item) {
        self.items.set(item.id, item);
        return self.items.get(item.id);
      },

      /**
       * Fetch item by id (from cache or network)
       * @param {string} id Hackernews item id
       * @param {number} index Index of item in list
       * @return {Promise}
       */
      fetchItem(id: string, { force = true, metadata = false } = {}) {
        return flow(function* () {
github birkir / kvikmyndr-app / src / store / in-theaters.ts View on Github external
interface IShowtimeFromDb {
  playingAt: string;
}

interface IMovieFromDb {
  id: string;
  showtimes: IShowtimeFromDb[];
}

export const InTheaters = types.model('InTheaters', {
  loading: false,
  loaded: false,
  isOffline: false,
  isCache: false,
  dates: types.map(types.model('DateOfMovies', {
    date: types.identifier,
    movies: types.map(types.model('MovieRef', {
      id: types.identifier,
      movie: types.reference(Movie, {
        get(identifier: string) {
          return Movies.movies.get(identifier) as typeof Movie.Type;
        },
        set(value: typeof Movie.Type) {
          return value.id;
        },
      }),
    })),
  })),
})
.views(self => ({
  moviesForDate(date: Date) {
github naguvan / react-mst-form / packages / reactive-json-schema / src / Object / Object.ts View on Github external
const XObject = types
      .compose(
        "Object",
        createValue(
          "object",
          types.map(types.frozen),
          {}
        ),
        types.model({
          additionalProperties: types.maybe(
            types.union(types.boolean, types.late(createType))
          ),
          maxProperties: types.maybe(types.number),
          minProperties: types.maybe(types.number),
          properties: types.maybe(
            types.map(types.late(createType))
          ),
          required: types.maybe(types.array(types.string))
        })
      )
      .actions(it => ({
        updateProps(value: object | null) {
          if (value) {
            keys(value).forEach(key => {
              const type = it.properties!.get(key);
              if (type) {
                return (type as any).setValue((value as any)[key]);
              }
            });
          }
        }
      }))
github codesandbox / codesandbox-client / packages / app / src / app / store / modules / profile / model.js View on Github external
givenLikeCount: types.number,
      forkedCount: types.number,
      badges: types.array(
        types.model({
          visible: types.boolean,
          name: types.string,
          id: types.string,
        })
      ),
      avatarUrl: types.string,
    })
  ),
  currentProfileId: types.maybeNull(types.string),
  notFound: types.boolean,
  isLoadingProfile: types.boolean,
  sandboxes: types.map(types.map(types.array(Sandbox))),
  likedSandboxes: types.map(types.map(types.array(Sandbox))),
  userSandboxes: types.array(
    types.model({
      id: types.string,
      title: types.maybeNull(types.string),
      insertedAt: types.string,
      updatedAt: types.string,
    })
  ),
  currentSandboxesPage: types.number,
  currentLikedSandboxesPage: types.number,
  isLoadingSandboxes: types.boolean,
  sandboxToDeleteId: types.maybeNull(types.string),
};
github zooniverse / front-end-monorepo / packages / lib-classifier / src / store / WorkflowStepStore.js View on Github external
import { autorun } from 'mobx'
import { addDisposer, getRoot, isValidReference, onAction, types } from 'mobx-state-tree'

import Step from './Step'
import taskRegistry, { taskModels } from '@plugins/tasks'

const taskTypes = types.union(...taskModels)

const WorkflowStepStore = types
  .model('WorkflowStepStore', {
    active: types.safeReference(Step),
    steps: types.map(Step)
  })
  .views(self => ({
    get activeStepTasks () {
      const validStepReference = isValidReference(() => self.active)
      if (validStepReference) {
        return self.active.tasks
      }

      return []
    },

    isThereANextStep () {
      const nextStep = self.getNextStepKey()
      return nextStep && nextStep !== 'summary'
    },
github charlessolar / eShopOnContainersDDD / src / Web / src / app / parts / catalog / models / brands.ts View on Github external
export { BrandType, BrandModel };

const debug = new Debug('catalog brands');

export interface BrandListType {
  entries: Map;
  loading: boolean;
  list: (term?: string, id?: string) => Promise<{}>;
  add: (brand: BrandType) => void;
  remove: (id: string) => Promise<{}>;
  clear(): void;
  readonly projection: { id: string, label: string}[];
}
export const BrandListModel = types
  .model('Catalog_Brand_List', {
    entries: types.optional(types.map(BrandModel), {}),
    loading: types.optional(types.boolean, true)
  })
  .views(self => ({
    get projection() {
      return Array.from(self.entries.values()).map(x => ({ id: x.id, label: x.brand }));
    }
  }))
  .actions(self => {
    const list = flow(function*(term?: string, id?: string) {
      const request = new DTOs.ListCatalogBrands();

      request.term = term;
      request.id = id;

      self.loading = true;
      try {