Skip to content

Integrate Meteor reactive data with MobX for simple yet highly optimized state management

License

Notifications You must be signed in to change notification settings

meteor-space/tracker-mobx-autorun

Repository files navigation

Tracker MobX autorun

Integrate Meteor reactive data (Tracker-aware reactive data sources) with MobX for simple yet highly optimized state management

MobX and Tracker can both autorun code when a dependency changes, however caching a copy of Meteor reactive data in a MobX store requires a significant amount of boilerplate. This package handles the complexity and provides an autorun that can be triggered by a change to either a MobX observable or Meteor reactive data source.

Usage

import { Meteor } from 'meteor/meteor';
import { observable, useStrict } from 'mobx';
import autorun, { observe } from 'meteor/space:tracker-mobx-autorun';

// Optionally MobX strict mode makes state in the store immutable, in that case
// state can ony be changed by MobX actions
useStrict(true);

const Todos = new Mongo.Collection('todos');

const state = observable({
  selectedProjectId: null,
  projectTodos: []
});

const syncProjectTodos = autorun(() => {
  const projectId = state.selectedProjectId;
  const handle = Meteor.subscribe('todos', { projectId });
  const cursor = Todos.find({ projectId });
  observe('todosAutorun', state.projectTodos, handle, cursor);
});

// Starting autorun on startup or when needed
Meteor.startup(() => {
  if (Meteor.isClient) syncProjectTodos().start();
});

// Stopping autorun
syncProjectTodos().stop();

Before and After

aNativ image Trello card from April 2016 - Before and after refactoring

  • React container component displays the currently selected project name.
  • Original implementation used Tracker.Component.
  • Application code for managing subscriptions and client state was reduced by 80%
  • Number of unnecessary re-renderings reduced to 0 thanks to mobx-react observer, this post explains how to use it properly.

Installation

meteor add space:tracker-mobx-autorun

npm install --save mobx mobx-react

Meteor 1.3 +

Developed with sponsorship from dyzio - social video marketing made easy

About

Integrate Meteor reactive data with MobX for simple yet highly optimized state management

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published