4

I'm trying to incorporate the async/await syntax into my Redux actions but, for some reason, it's not working. I cannot for the life of me see what is wrong with the following:

const actions = {
    load: async (staff, date) => dispatch => {
        const data = {
            dateFrom: date,
            dateTo: date,
            person: staff,
            personType: 'staff'
        };

        const events = utils.getDataPromise('json/events/load', data);
        const classes = utils.getDataPromise('json/timetable/load', data);

        dispatch({
            type: actions.MYDAY_LOAD,
            staff,
            date: date || new Date(),
            events: await events,
            classes: await classes
        });
    },
}

The utils function definitely returns a promise.

Steven Laidlaw
  • 450
  • 3
  • 11
  • are you using thunk? – Isaac Aug 14 '17 at 23:57
  • @isaac Yes, I'm using thunk. The error I'm getting is with the `await` keywords -- even my IDE is telling me they are in the wrong spot. – Steven Laidlaw Aug 14 '17 at 23:58
  • 1
    `load` is an async function that returns a non async function, move your async before `dispatch`. Check this [question](https://stackoverflow.com/questions/42489918/async-await-inside-arraymap) – Gerardo Aug 15 '17 at 00:00
  • @Gerado Thanks, that worked perfectly. Feel free to write it in an answer and I'll mark it accepted. – Steven Laidlaw Aug 15 '17 at 00:02
  • Interesting. A working example I have in front of me is something like this: `export function myAction() { let value = await something(); return dispatch(value); }` – Isaac Aug 15 '17 at 00:03

1 Answers1

6

This is a common mistake due to arrow functions syntax.

Your load function is async but returns an anonymous arrow function dispatch => {...}.

await only works when it's inside an async function and your await calls are inside the anonymous returned function which is not async that's why it doesn't work. Move async just before dispatch and that should work.

const actions = {
    load: (staff, date) => async dispatch => {...}
    //                     ^^^^^ move it here
...
}
Gerardo
  • 979
  • 1
  • 7
  • 15