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.

5
  • are you using thunk?
    – Isaac
    Aug 14, 2017 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. Aug 14, 2017 at 23:58
  • 1
    load is an async function that returns a non async function, move your async before dispatch. Check this question
    – Gerardo
    Aug 15, 2017 at 0:00
  • @Gerado Thanks, that worked perfectly. Feel free to write it in an answer and I'll mark it accepted. Aug 15, 2017 at 0: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, 2017 at 0:03

1 Answer 1

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
...
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.