Store.subscribe vs Actions firing actions #597

Closed
grgur opened this Issue Aug 21, 2015 · 2 comments

Comments

3 participants
@grgur

grgur commented Aug 21, 2015

Let's say that a completed async operation should fire another action based on new data. While I would prefer to do this with Store.subscribe, I think the "listener" is to raw, given that I might end up observing state diff in multiple actions ("files"), which is wasteful. On that note, it'd be kinda useful if store.subscribe would fire with an argument containing the diff in state calculated in a single place.

My question here is again about the healthy pattern usage. Do you folks think it's viable to import an action and fire it from another action? Example below:

import { RECEIVE_LOCATION } from '../constants/Types';
import { defaultPosition } from '../constants/Geo';
import { fetchMeetupGroups } from './Meetup';
import store from '../stores';

function requestGeolocation() {
  return function(dispatch) {
    navigator.geolocation.getCurrentPosition(function(position) {
      const { latitude, longitude } = position.coords;

      dispatch({
        type: RECEIVE_LOCATION,
        coords: {
          latitude: latitude,
          longitude: longitude,
          inProgress: false,
        },
      });

      dispatch(fetchMeetupGroups({latitude, longitude}));
    });
  };
}

function getDefaultGeolocation() {
  return {
    type: RECEIVE_LOCATION,
    ...defaultPosition,
  };
}

export function getGeolocation() {
  if (!navigator.geolocation) {
    return store.dispatch(getDefaultGeolocation());
  }
  return store.dispatch(requestGeolocation());
}

In this case requestGeolocation() callback fired fetchMeetupGroups from another action module.

@johanneslumpe

This comment has been minimized.

Show comment
Hide comment
@johanneslumpe

johanneslumpe Aug 21, 2015

Collaborator

If these actions are inherently coupled together and always have to happen combined, I do not see why you couldn't go down this route. The thunk middleware was made to exactly support cases like this where you have multiple dispatches going on.

Collaborator

johanneslumpe commented Aug 21, 2015

If these actions are inherently coupled together and always have to happen combined, I do not see why you couldn't go down this route. The thunk middleware was made to exactly support cases like this where you have multiple dispatches going on.

@gaearon gaearon added the question label Aug 21, 2015

@gaearon

This comment has been minimized.

Show comment
Hide comment

@gaearon gaearon closed this Aug 21, 2015

@reduxjs reduxjs deleted a comment from melitus Apr 4, 2018

@reduxjs reduxjs locked and limited conversation to collaborators Apr 4, 2018

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.