1
votes

Some background: I am able to get everything to work when I use simple .then() chaining on fetch and dispatching the responses. The error I get now is when I am trying to make my action async, and using await on the promises .

Note: I am using redux thunk.

actions.js:

export const onLoginPressed = async (params) => async (dispatch) => {
  try {
    const loginResp = await fetch("http://localhost:8000/api-token-auth/", {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(params)
    })

    let res = await loginResp.text();
    if (response.status >= 200 && response.status < 300) {
      let accessToken = res;
      dispatch(storeToken(accessToken));
    } else {
      let error = res;
      dispatch(failToken())
      throw error;
    }
  } catch (e) {
    console.log(e)
  }

}

export const failToken = () => {
  return {
    type: FAIL_TOKEN
  }
}

export const storeToken = (token) => {
  return {
    type: CREATE_TOKEN,
    token: token
  }
}
1
async will make sure a promise is returned under the hood. Have you tried removing async from the async (params)? - Tholle
Can you provide your code related to your store object? It might be a setup issue that causing this problem - Timothy Alfares
yeah I just tried that and it works! - Christian Lessard

1 Answers

1
votes

The async keyword will make sure a promise is returned, and you don't want to return a promise but a function.

Remove the async keyword from the first function and it will work as expected.

export const onLoginPressed = (params) => async (dispatch) => {
  // ...
}