Search code examples
javascriptnode.jsreduxmiddleware

Redux middleware with callback


I really like the concept of having actions written like this:

function signUp(data, callback) { 
return {
    [CALL_API]: {
      type: 'SOME_TYPE',
      url: `/api/account/signup`, 
      method: 'POST',
      data: data

    }
  }
}

But for thing like signUp I don't want to modify/touch the store to get a callback from server


In my React component I have an action that calls the api through an action and changes the state.

  this.signUp($(form).serialize(), function(data) {  this.setState({response: data});   }.bind(this))

and action signUp looks like this

function signUp(data, callback) { 
 postRequest(
    '/api/account/signup', 
    data, 
    'POST', 
    callback)
}


function postRequest(url, data, method, callback) { 
callback(true); //// just testing  
}

As you can see the syntax and the length of code isn't pretty compared to the first one


Question: Is there a way to modify the redux middleware OR have an alternative JSON function (similar to CALL_API) to accept callbacks to component without touching the store? I really want to use the CALL_API syntax :)


Solution

  • You can write middleware to intercept actions and do some work without modifying the store's state.

    // Action creator    
    function signUp(data, callback) { 
      return {
          type: CALL_API
          url: '/api/account/signup', 
          method: 'POST',
          data: data,
          callback: callback
      }
    }
    
    // Middleware
    const actionInterceptor = store => next => action => {
        if (action.type === CALL_API) {
            postRequest(action.url, action.method, action.data, action.callback);
        }
        else {
            return next(action);
        }
    }
    
    ...
    
    const store = createStore(reducer, initialState, applyMiddleware(actionInterceptor));