Search code examples
reactjsreduxmiddlewareredux-thunk

Function inside of Redux middleware not working


I'm trying to make some middleware which refreshes my JWT if it's expired. I currently have this middleware:

import { isTokenExpired, refreshToken } from '../modules/auth/auth.service'
export const jwt = store => next => action => {
    if (typeof action === 'function') {
      console.log("Middleware triggered:", action);
      var theState = store.getState();
      if (theState.auth && theState.auth.authToken && isTokenExpired(theState.auth.authToken)) {
        console.log('This is logging')
        //this function is not being called
        refreshToken(theState.auth.refreshToken);
      }
    }
    return next(action)
}

I wish to call the refreshToken() function which will start the process, but so far even the console.log() inside the refreshToken is not calling:

export const refreshToken = (refreshToken) => dispatch => {
  console.log('Not logging')
}

Also, inside the refreshToken function will be asynchronous while it refreshes the token. I was thinking of setting a "REFRESH_TOKEN_PENDING" type in the reducer, and once the response is received send "REFRESH_TOKEN_SUCCESS" to the reducer. Will this be possible with the middleware?

Thanks


Solution

  • You have to dispatch refreshToken(). If you do have access to dispatch() into jwt function you should call it like dispatch(refreshToken()).

    Considering that I'm not sure how you are triggering the jwt action, I think this is a valid solution of how you can easily trigger middleware functions inside actions:

    // ================
    //  Container file
    // ================
    import {connect} from "react-redux";
    import { bindActionCreators } from "redux";
    // ... other 
    
    function mapActionsToProps(dispatch) {
      return bindActionCreators({
        jwt: path_to_actions_file.jwt
    }, dispatch)}
    
    const mapStateToProps = (state) => ({
      // ... your state properties
    });
    
    export default connect(mapStateToProps, mapActionsToProps)(YourComponent); // <== YourComponent has to be a React Component
    
    // ==============
    //  Actions file
    // ==============
    export const setConvertTypeActive = store => dispatch => {
      console.log('This is logging.');
      dispatch(refreshToken("md5Token"));
    }
    
    export const refreshToken = refreshToken => dispatch => {
      console.log('Should log now.');
    }
    

    And regarding your last question, yeah, you can create middlewares similar to refreshToken action for setting some statuses on reducer. Check the code below:

    // ============== 
    //  Actions file
    // ==============
    export const refreshToken= {
      pending: () => ({
        // "REFRESH_TOKEN_PENDING"
      }),
      success: (data) => ({
        // "REFRESH_TOKEN_SUCCESS"
      })  
    };