0

I'm using redux with redux-thunk for async actions.

And I found a lot of similar questions on this site, also on some other blogs - some people suggest not to use getState() in action-creator because it's anti-pattern, from other hand other people says that it's OK in some specific cases. But I still can't understand is it OK to do it in my specific case.

I have auth reducer which contains userId inside it.

And this is my action creator:

export const getUserHobbies= () => (dispatch, getState )=> {

    const currentUserId = getState().auth.userId;

    dispatch({
        type: GET_HOBBIES_REQUEST
    });

    return fetch(`api/hobbies/?userId=${currentUserId}`)
        .then (json => { 
           //...
        })
        .catch( e => {
           //...
        })
};

As you can see I need current user ID for doing AJAX request, and I'm retrieving current user ID using getState() in action creator. Is it OK? Or better connect userId to my component and pass this value to action-creator from component?

WelcomeTo
  • 19,843
  • 53
  • 170
  • 286
  • In your case you could simply pass the userId from the container where you are calling getUserHobbies – Shubham Khatri Jan 25 '18 at 13:24
  • I see no difference. i use both method but if i have to chose i will prefer to use `getState` unless of course i need to use the value in my container. and my reason is that it makes this call reusable; if more than one components calls its you won't need to start passing in userId props they may otherwise not need and you can change the behavior of the action from just one place if need be. – Femi Oni Jan 25 '18 at 13:31
  • 1
    Have you read [this answer](https://stackoverflow.com/a/35674575/3148807)? it posted by dan abramov, the creator of `redux`. – Sagiv b.g Jan 25 '18 at 13:38

1 Answers1

-1

If you feel a need to access internal state of component from outside of it (action creator), I would argue that such state should be placed into Redux store. So you can subscribe to it's updates and pass it into action creator as parameter (as @Marko Niciforovic mentioned).

After moving that state into Redux, your code will be Redux compliant.

EDIT (reaction on comment): If your state is ID of currently logged user, I can imagine that such information will be used a lot. I would consider using HTML5 session storage, local storage for such state.

luboskrnac
  • 23,973
  • 10
  • 81
  • 92
  • `userId` is already inside Redux state, and it lives here just as constant and can not be changed. I need it only for technical purposes - construct correct URL for AJAX call. – WelcomeTo Jan 25 '18 at 14:17
  • I just don't want to pass it to component via `connect` and send back from component to `actionCreator`. No need for this round-trip. It will not be changed anyway. It is just ID of currently logged in user. Or you think it's still better to pass it to component and then to actionCreator? – WelcomeTo Jan 25 '18 at 15:08