How to use the mobx-state-tree.flow 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 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 charlessolar / eShopOnContainersDDD / src / Web / src / app / parts / catalog / models / basket.ts View on Github external
.actions(self => {

    const init = flow(function*() {
      const client = getEnv(self).api as ApiClientType;

      try {
        const request = new DTOs.InitiateBasket();
        request.basketId = uuid();
        // set beforehand so init is only run once
        self.basketId = request.basketId;

        yield client.command(request);
      } catch (error) {
        self.basketId = undefined;
        debug('received http error: ', error);
        throw error;
      }
    });
    const get = flow(function*() {
github zooniverse / front-end-monorepo / packages / app-content-pages / src / shared / stores / Publications / Publications.js View on Github external
}

        self.loadingState = asyncStates.success
        self.response = response
      } catch (error) {
        const servername = get(error, 'response.res.client.servername')
        if (servername && servername.includes('panoptes')) {
          console.error('Error fetching avatars from Panoptes,', error.response.statusCode)
        } else {
          console.error(error)
          self.loadingState = asyncStates.error
        }
      }
    }),

    fetchAvatars: flow(function * fetchAvatars () {
      const panoptesClient = getRoot(self).panoptesClient
      const panoptesIds = self.panoptesIds.join(',')

      const params = {
        query: {
          cards: true,
          id: panoptesIds,
          page_size: 100
        }
      }
      const response = yield panoptesClient.projects.get(params)
      self.processAvatars(response)
    }),

    linkEntryToParent (entry, entryType, parentType) {
      const entryId = entry.sys.id
github wp-pwa / wp-pwa / core / packages / one-signal / pwa / stores / index.js View on Github external
'Something was wrong while initializing OneSignal:\n',
          error,
        );
      }

      self.areEnabled = yield window.OneSignal.isPushNotificationsEnabled();

      window.OneSignal.on('notificationPermissionChange', permissionChange => {
        if (permissionChange.to === 'denied') self.disable();
        else if (permissionChange.to === 'granted') self.enable();
      });
      window.OneSignal.on('customPromptClick', ({ result }) => {
        if (result === 'denied') self.disable();
      });
    }),
    toggleEnabled: flow(function* toggleNotifications() {
      self.areEnabled = !self.areEnabled;

      if (self.areEnabled) {
        const permission = yield window.OneSignal.getNotificationPermission();
        if (permission === 'denied') {
          console.warn('Notifications denied in browser!');
          self.areEnabled = false;
          return;
        }
        window.OneSignal.registerForPushNotifications();
        yield window.OneSignal.setSubscription(true);
      } else {
        yield window.OneSignal.setSubscription(false);
      }
    }),
    disable() {
github Feverqwe / tSearch / src / stores / Explorer / ExplorerQuickSearchStore.js View on Github external
}).actions((self) => {
  return {
    setQuickSearch(value) {
      self.quickSearch = value;
    },
    fetch: flow(function* () {
      self.state = 'pending';
      try {
        const storage = yield storageGet({quickSearch: {}});
        if (isAlive(self)) {
          try {
            self.quickSearch = storage.quickSearch;
          } catch (err) {
            logger.error('set quickSearch error, quickSearch will cleared', err);
            self.quickSearch = {};
          }
          self.state = 'done';
        }
      } catch (err) {
        logger.error('fetch error', err);
        if (isAlive(self)) {
          self.state = 'error';
github grafana / grafana / public / app / stores / TeamsStore / TeamsStore.ts View on Github external
}
    }),

    addGroup: flow(function* load(groupId: string) {
      const backendSrv = getEnv(self).backendSrv;
      yield backendSrv.post(`/api/teams/${self.id}/groups`, { groupId: groupId });
      self.groups.set(
        groupId,
        TeamGroup.create({
          teamId: self.id,
          groupId: groupId,
        })
      );
    }),

    removeGroup: flow(function* load(groupId: string) {
      const backendSrv = getEnv(self).backendSrv;
      yield backendSrv.delete(`/api/teams/${self.id}/groups/${groupId}`);
      self.groups.delete(groupId);
    }),
  }));
github baidu / amis / src / store / form.ts View on Github external
if (!item.validated || forceValidate) {
          yield item.validate();
        }
      }

      if (hooks && hooks.length) {
        for (let i = 0, len = hooks.length; i < len; i++) {
          yield hooks[i]();
        }
      }

      self.validating = false;
      return self.valid;
    });

    const validateFields: (fields: Array) => Promise = flow(
      function* validateFields(fields: Array) {
        self.validating = true;
        const items = self.items.concat();
        let result: Array = [];
        for (let i = 0, len = items.length; i < len; i++) {
          let item = items[i] as IFormItemStore;

          if (~fields.indexOf(item.name)) {
            result.push(yield item.validate());
          }
        }
        self.validating = false;
        return result.every(item => item);
      }
    );
github zooniverse / front-end-monorepo / packages / app-project / stores / Collections.js View on Github external
createFavourites: flow(function * createFavourites (subjectIds = []) {
        const { project } = getRoot(self)
        const options = {
          display_name: `Favorites ${project.slug}`,
          favorite: true,
          private: true
        }
        const favourites = yield newCollection(options, subjectIds)
        return favourites
      }),

      searchCollections: flow(function * searchCollections (query) {
        self.collections = yield fetchCollections(query)
      }),

      fetchFavourites: flow(function * fetchFavourites () {
        const { project, user } = getRoot(self)
        const query = {
          favorite: true,
          project_ids: [project.id],
          owner: user.login
        }
        let [favourites] = yield fetchCollections(query)
        if (favourites) {
          self.favourites = Collection.create(favourites)
        } else {
          favourites = yield self.createFavourites()
          self.favourites = Collection.create(favourites)
        }
      }),

      addSubjects: flow(function * addSubjects (id, subjectIds) {
github jsdevkr / gitCodeShare.com / stores / AppStore.ts View on Github external
.actions(self => {
    function addStarredGists(gist: IGist) {
      if (self.starredGists.get(gist.id + '')) {
        self.starredGists.set(gist.id + '', gist);
      } else {
        self.starredGists.put(gist);
      }
    }

    const getStar = flow(function*() {
      const star = yield self.provider.GithubRequest.getStarNum();
      self.star = star;
    });

    const getFork = flow(function*() {
      const fork = yield self.provider.GithubRequest.getForkNum();
      self.fork = fork;
    });

    const init = flow(function*() {
      yield getStar();
      yield getFork();
      self.loaded = true;
      return {};
    });