npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

meteor-redux-middlewares

v3.0.7

Published

Middlewares to sync meteor reactive sources with redux store

Downloads

479

Readme

meteor-redux-middlewares Build Status Codecov

Middlewares to sync meteor reactive sources with redux store.

Installation

Using npm

npm i meteor-redux-middlewares --save

Using yarn

yarn add meteor-redux-middlewares

Using meteor

meteor add samy:redux-middlewares

Table of contents

Example of use

All the following code is available on the demo repository.

Step 1: apply middlewares
// File '/imports/store/index.js'
import { Tracker } from 'meteor/tracker';
import createReactiveMiddlewares from 'meteor-redux-middlewares';
// or: import createReactiveMiddlewares from 'meteor/samy:redux-middlewares';
import { applyMiddleware, createStore, compose } from 'redux';

// Of course, you can use other middlewares as well
import thunk from 'redux-thunk';
import createLogger from 'redux-logger';

import rootReducer from '/imports/reducers';

// We use an injection pattern to avoid any direct dependency on the meteor
// build tool, or version of tracker within the package.
//
// This way you should be able to use your meteor version, a community npm
// version, the future extracted official mdg package etc...
const {
  sources,
  subscriptions,
} = createReactiveMiddlewares(Tracker);

const store = createStore(rootReducer, compose(
  applyMiddleware(sources, subscriptions, thunk, logger)
));

export default store;
Step 2: create actions
// File '/imports/actions/user/load.js'
import { Meteor } from 'meteor/meteor';
import { registerReactiveSource } from 'meteor-redux-middlewares';

export const USER_REACTIVE_SOURCE_CHANGED = 'USER_REACTIVE_SOURCE_CHANGED';

export const loadUser = () =>
  registerReactiveSource({
    key: 'user',
    get: () => Meteor.user() || {},
  });

This action will automatically be intercepted by the sources middleware. Your get function is running inside a Tracker.autorun, that means each time the data will change, the middleware will dispatch an action with the _REACTIVE_SOURCE_CHANGED suffix. In this example, we are dispatching an action with a key of user, so we have to handle the USER_REACTIVE_SOURCE_CHANGED action in our reducer.

// File '/imports/actions/home/posts/load.js'
import { Meteor } from 'meteor/meteor';
import { startSubscription } from 'meteor-redux-middlewares';
import { Posts } from '/imports/api/collections/posts';

export const HOME_POSTS_SUBSCRIPTION_READY = 'HOME_POSTS_SUBSCRIPTION_READY';
export const HOME_POSTS_SUBSCRIPTION_CHANGED = 'HOME_POSTS_SUBSCRIPTION_CHANGED';
export const HOME_POSTS_SUB = 'home.posts';

export const loadHomePosts = () =>
  startSubscription({
    key: HOME_POSTS_SUB,
    get: () => Posts.find().fetch(),
    subscribe: () => Meteor.subscribe(HOME_POSTS_SUB),
  });

This action will automatically be intercepted by the subscriptions middleware. Your get function is running inside a Tracker.autorun, that means each time the data will change, the middleware will dispatch an action with the _SUBSCRIPTION_CHANGED suffix. In the same way, each time the subscription will be ready (or not), the middleware will dispatch an action with the _SUBSCRIPTION_READY suffix. In this example, we are dispatching an action with a key of home.posts, so we have to handle the HOME_POSTS_SUBSCRIPTION_READY and HOME_POSTS_SUBSCRIPTION_CHANGED actions in our reducer.

Step 3: create reducers
// File '/imports/reducers/user.js'
import { USER_REACTIVE_SOURCE_CHANGED } from '/imports/actions/user/load';

const initialState = {
  ready: false,
};

export function user(state = initialState, action) {
  switch (action.type) {
    case USER_REACTIVE_SOURCE_CHANGED:
      return {
        ...action.payload,
        ready: true,
      };
    default:
      return state;
  }
}

With the reactive sources, we can access to the data returned by our get function inside the action.payload attribute.

// File '/imports/reducers/home.js'
import { STOP_SUBSCRIPTION } from 'meteor-redux-middlewares';

import {
  HOME_POSTS_SUBSCRIPTION_READY,
  HOME_POSTS_SUBSCRIPTION_CHANGED,
  HOME_POSTS_SUB,
} from '/imports/actions/home/posts/load';

const initialState = {
  ready: false,
  posts: [],
  postsSubscriptionStopped: false,
};

export function home(state = initialState, action) {
  switch (action.type) {
    case HOME_POSTS_SUBSCRIPTION_READY:
      return {
        ...state,
        ready: action.payload.ready,
      };
    case HOME_POSTS_SUBSCRIPTION_CHANGED:
      return {
        ...state,
        posts: action.payload,
      };
    case STOP_SUBSCRIPTION:
      return action.payload === HOME_POSTS_SUB
        ? { ...state, postsSubscriptionStopped: true }
        : state;
    default:
      return state;
  }
}

With the subscriptions, we can access to:

  • the data returned by our get function inside the action.payload attribute.
  • the readiness state of the subscription inside the action.payload.ready attribute.

Stop a subscription

You can stop a subscription by dispatching the stopSubscription action, for example inside a container component:

import { connect } from 'react-redux';
import { stopSubscription } from 'meteor-redux-middlewares';
import { loadHomePosts, HOME_POSTS_SUB } from '/imports/actions/home/posts/load';
import { HomePageComponent } from '/imports/ui/components/pages/HomePageComponent';

const mapStateToProps = state => ({
  postsReady: state.home.ready,
  posts: state.home.posts,
  postsSubscriptionStopped: state.home.postsSubscriptionStopped,
});

const mapDispatchToProps = dispatch => ({
  loadPosts: () => {
    dispatch(loadHomePosts());
  },
  stopPostsSubscription: () => {
    dispatch(stopSubscription(HOME_POSTS_SUB));
  },
});

export const HomePageContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)(HomePageComponent);  

Pass extra data to the reducer

If you need to pass some extra data to the reducer with the subscriptions middleware when your subscription's ready state changes, you can add an onReadyData attribute in your action:

import { Meteor } from 'meteor/meteor';
import { startSubscription } from 'meteor-redux-middlewares';
import { Posts } from '/imports/api/collections/posts';

export const HOME_POSTS_SUBSCRIPTION_READY = 'HOME_POSTS_SUBSCRIPTION_READY';
export const HOME_POSTS_SUBSCRIPTION_CHANGED = 'HOME_POSTS_SUBSCRIPTION_CHANGED';
export const HOME_POSTS_SUB = 'home.posts';

export const loadHomePosts = () =>
  startSubscription({
    key: HOME_POSTS_SUB,
    get: () => Posts.find().fetch(),
    subscribe: () => Meteor.subscribe(HOME_POSTS_SUB),
    onReadyData: () => ({
      extraKey1: 'extraValue1',
      extraKey2: 'extraValue2',
    }),
  });

Then in your reducer, you can access to the extra data by using the payload.data attribute;

import {
  HOME_POSTS_SUBSCRIPTION_READY,
  HOME_POSTS_SUBSCRIPTION_CHANGED
} from '/imports/actions/home/posts/load';

const initialState = {
  ready: false,
  posts: [],
};

export function home(state = initialState, action) {
  switch (action.type) {
    case HOME_POSTS_SUBSCRIPTION_READY:
      // This will log: Object { extraKey1="extraValue1", extraKey2="extraValue2" }
      console.log(action.payload.data);

      return {
        ...state,
        ready: action.payload.ready,
      };
    case HOME_POSTS_SUBSCRIPTION_CHANGED:
      return {
        ...state,
        posts: action.payload
      };
    default:
      return state;
  }
}

Credits

Based on the work of Gildas Garcia (@djhi) on his My-Nutrition project. Thanks to Kyle Chamberlain (@Koleok) for his contribution.