0

I have a chat-app that uses React, Redux and Firebase. I'm also using thunkmiddleware to do the async updates of the state with Firebase. I successfully get everything I need, except that everything depends of a previously hard-coded variable.

The question is, how can I call inside my ActionCreators the getState() method in order to retrieve a piece of state value that I need in order to fill the rest of my states?

I currently have my auth: { uid = 'XXXZZZYYYY' }... I just need to call that like

getState().auth.uid

however that doesn't work at all.

I tried a lot of different questions, using mapDispatchToProps, etc. I can show my repo if needed.

Worth to mention that I tried following this other question without success. Accessing Redux state in an action creator? This is my relevant current code:

const store = createStore(  
    rootReducer,
    defaultState,
    applyMiddleware(thunkMiddleware));

And

function mapDispatchToProps(dispatch) {
    watchFirebase(dispatch); // to dispatch async Firebase calls
    return bindActionCreators(actionCreator, dispatch);
}  
const App = connect(mapStateToProps, mapDispatchToProps)(AppWrapper);

Which I am exporting correctly as many other not pure functions work correctly. For instance, this works correctly:

export function fillLoggedUser() {  
      return (dispatch, getState) => {
      dispatch({
        type: C.LOGGED_IN,
      });
    }
  }

However as suggested below, this doesn't do a thing:

const logState = () => ( dispatch, getState ) => {  
       console.log(getState());  
  };  
Community
  • 1
  • 1
villancikos
  • 519
  • 1
  • 6
  • 13
  • as suggested in the SO answer you linked, the simplest way of doing this is to use redux-thunk. If you already tried it please post some code so we can help you on your specific problem. – fabio.sussetto Mar 27 '17 at 23:45

1 Answers1

0

In general your thunked action creator should look something like the below (I have used a post id as an example parameter):

const getPost = ( postId ) => ( dispatch, getState ) => {
    const state = getState();
    const authToken = state.reducerName.authToken;
    Api.getPost(postId, authToken)
    .then(result => {
        // where postRetrieved returns an action
        dispatch(postRetrieved(result));
    });
};

If this is similar to what you have then I would log your state out and see what is going on with a simple thunk.

const logState = () => ( dispatch, getState ) => {
    console.log(getState());
};
Alex Young
  • 4,009
  • 1
  • 16
  • 34