anon
anon

Reputation: 2343

Multiple AJAX requests with React Redux

I want to make requests to two different APIs. I then need to organize that data. I'm using redux-promise.

Currently, I have a function, calls two other functions that do the AJAX request:

export function fetchEstimates(input) {
  let firstRequest = fetchFirstRequest(input);
  let secondRequest = fetchFirstRequest(input);

  return {
    type: FETCH_DATA,
    payload: {
      firstRequest: firstRequest
      secondRequest: secondRequest
    }
  }
}

Unfortunately, by putting both requests in an object, I can't seem to access the results.

export default function(state = [], action) {

  switch (action.type) {
    case FETCH_DATA:
      // console.log(action.firstRequest);
      // console.log(action.secondRequest);
      return result;
  }
  return state;
}

As I toggle the object in dev tools, I come to this:

[[PromiseStatus]]:"resolved"
[[PromiseValue]]:Object

I can continue to toggle the options, but I can't seem to access them in my code.

If in my payload, I just return this

payload: firstRequest

I don't have issues. But of course, I need both requests. Any ideas. What is a good approach to handle this?

Upvotes: 1

Views: 1088

Answers (2)

markerikson
markerikson

Reputation: 67469

If you look at the source for redux-promise, you'll see that it assumes you've provided a promise as the "payload" field in your action. You're instead providing an object with two promises as sub-fields under "payload". I'm assuming that you're really interested in having both promises resolve, and then passing both results to the reducer. You'd want to use Promise.all to create a new promise that receives the results of both original promises as an argument, then use that promise as your payload. The reducer would then receive something like: {type : "DATA_RECEIVED", payload : [response1, response2]}.

Upvotes: 1

Steven
Steven

Reputation: 1596

You need some sort of middleware to deal with Promises (like redux-thunk), and wrap the promises in Promise.all to wait until they're both resolved. Let me know if you need a code example.

Upvotes: 0

Related Questions