3

Hi I am very new to api calls and I am starting to use axios to get a simple deck of cards! I am trying to do a simple axios call, and when I console log my res, it gives me what I need. But when i return it, it gives me Promise { < pending > } . From what I have seen, it is because it is a async promise, and the promise is getting resolved but because it is async, it moves on to the next line of code before returning the actual data? Please correct me if I'm wrong! Some clarification would be awesome. Thanks in advance!

async function getData() {
    const result = await axios('https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1');
    console.log(result.data);
    return await result.data;
}

my actions in redux

export function getNewDeck() {
    return {
        type: GET_NEW_DECK,
        payload: getData().then( res => {
                 return res.data
            })
    }
}

Then in my reducer, my action.payload returns the Promise { < pending > }

yabna
  • 99
  • 3
  • 13
  • look up thunks it how you handle async actions https://github.com/reduxjs/redux-thunk – Joe Warner Jan 05 '19 at 20:25
  • 2
    All functions marked as `async` return a Promise, always, that's what `async` does. You need to `await getData()` or `getData.then(...)`. Also, you don't need the `await` in the `return await result.data;`. `result.data` is not an async call, so there's nothing to wait for – Matthew Herbst Jan 05 '19 at 20:27
  • I have Thunk as my middleware. – yabna Jan 05 '19 at 20:34
  • @MatthewHerbst Oh ok that makes a lot more sense! I updated my example to have the payload returning with a .then because if I put a await in front of it it says that await is a reserved word? But I am still getting a promise resolved.. – yabna Jan 05 '19 at 20:40

1 Answers1

6

Updated from comments

I believe you just need to change your export function to also be asynchronous and await on getData:

export async function getNewDeck() {
    const payload = await getData();
    return {
        type: GET_NEW_DECK,
        payload
    }
}
GenericUser
  • 3,003
  • 1
  • 11
  • 17
  • `(await getData()).data` probably to match the OPs code, but indeed a `getData` method should already return the data not something with a data property. – Bergi Jan 05 '19 at 20:58
  • 1
    Yes it does. Thank you! – yabna Jan 05 '19 at 21:07