0

I am making all API calls from a generic function and in some of the responses, a custom response header comes. Using this header, I need to make another API call. Can this be achieved by using Redux middleware?

// function 1
return ApiCaller.post('url').then(json => {
  dispatch(someAction(json));
})

// function 2
return ApiCaller.post('anotherurl').then(json => {
  dispatch(someOtherAction(json));
})

// ApiCaller
fetch(url).then(response => {
  // before this I want to make another post call with data as response 
  // header 'x' value
  return response;
}

In the middleware I would want to read a key from the response header and make another API call, is it possible?

Varsha
  • 53
  • 6
  • Would you mind sharing code or being little more descriptive? – Vinod Sobale Aug 03 '17 at 11:27
  • 1
    What exactly do you mean by "using redux middleware"? Do you want to create new middleware? Or do you mean by using existing middleware libs like redux-thunk or redux-saga? Generally, redux middleware is dealing with redux actions and not API calls per se. However library middlewares like redux-thunk or redux-saga can in turn make an api all and deal with the response. – Martin Kadlec Aug 03 '17 at 11:31
  • I mean can i make a custom middleware to achieve this? – Varsha Aug 03 '17 at 11:47
  • In theory and with open mind, you could possibly do something like that. But I still feel like it's not actually what you want :) ... can you describe what led you to thinking you should use custom middleware instead of e.g. dispatching another action that will do the second api call in case of the 'x' header? – Martin Kadlec Aug 03 '17 at 11:55
  • I just wanted to try it out because using a middleware looks like a much cleaner approach than calling another api call after the response comes. And well if this is not possible then I might call the api after the response comes anyway :) – Varsha Aug 03 '17 at 12:05

1 Answers1

0

You can store the first response in your redux store and then include the store in the ApiCaller to get the headers.