pauldijou / redux-act

An opinionated lib to create actions and reducers for Redux

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Is there a way to access the store from createAction?

littlebigbot opened this issue · comments

For example, I have this action creator init(), and I can't know the state when I dispatch it. In a normal action creator, I could return a function (dispatch, getState)=>{}.

The main use case for this is api/socket calls that are based on the current state of the app. There's usually workarounds except in a specific case I'm dealing with.

To answer the title question: no, there is not. That's because action creators are not aware of stores at all, they just create actions.

But you can still use your function with the Redux thunk middleware. Use redux-act only for actions which need to be handle by a reducer. For example, this is the example from Redux thunk:

const INCREMENT_COUNTER = 'INCREMENT_COUNTER';

function increment() {
  return {
    type: INCREMENT_COUNTER
  };
}

function incrementAsync() {
  return (dispatch, getState) => {
    setTimeout(() => {
      // Yay! Can invoke sync or async actions with `dispatch`
      dispatch(increment());
    }, 1000);
  };
}

You would only replace the first action creator with redux-act, not the second one:

var increment = createAction('increment');

function incrementAsync() {
  return (dispatch, getState) => {
    setTimeout(() => {
      // Yay! Can invoke sync or async actions with `dispatch`
      dispatch(increment());
    }, 1000);
  };
}

Thanks for the response!

I forgot that this solution with returning (dispatch, getState) => {} requires an additional middleware and I'm using redux-saga, so I'm injecting a saga selector that'll return an object that I can combine with the payload. I could avoid this if I built a really long switch case for all the socket actions I'm attempting to capture.

Glad to help. Closing the issue, don't hesitate to re-open if you need more help.

@littlebigbot

I'm using redux-saga, so I'm injecting a saga selector that'll return an object that I can combine with the payload. I could avoid this if I built a really long switch case for all the socket actions I'm attempting to capture.

Please give me your example, how to use redux-saga?