Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

async functions dispatch #107

Closed
davibe opened this issue Oct 20, 2016 · 5 comments
Closed

async functions dispatch #107

davibe opened this issue Oct 20, 2016 · 5 comments

Comments

@davibe
Copy link

davibe commented Oct 20, 2016

I discovered by accident that i can dispatch an async function like this

dispatch(async (dispatch, getState) => {
  const data = await networkReq();
  dispatch(updateWith(data));
});

I wonder if this is because babel translates it into something that works by accident, or what. It it safe to assume this is right ?

@TrySound
Copy link

TrySound commented Oct 20, 2016

@davibe It's quite safe. The same as you return promise and chain it. thunk doesn't matter how you execute your async code.

@davibe
Copy link
Author

davibe commented Oct 21, 2016

@TrySound so if i can do that, what is the meaning of my thunks return value ?

i.e. i could write

dispatch(async (dispatch, getState) => {
  const data = await networkReq();
  return { type: 'NEW_DATA', payload: data }
});

or without async

dispatch((dispatch, getState) => {
  return networkReq().then( (data) => { 
    return { type: 'NEW_DATA', payload: data }
  });
});

For some reason i expected thunk to dispatch my final action without calling dispatch myself. What should i use the return value for ? Thank you.

@TrySound
Copy link

@davibe thunk delegates dispatch calling to you.

const result = dispatch((dispatch, getState) => {
  return networkReq().then( (data) => { 
    return { type: 'NEW_DATA', payload: data }
  });
});
// result is equal to { type: 'NEW_DATA', payload: data }

But you can do this If you will use redux-promise. thunk doesn't do anything with promise or async api.

@davibe
Copy link
Author

davibe commented Oct 21, 2016

@TrySound i did also use redux-promise middleware but apparently when the promise is returned by an async-thunk it does not get dispatched anyway. I can dispatch(promise) but that's rather useless because since the thunk can be async i can dispatch(await getPromised()) with no additional middleware.

@davibe
Copy link
Author

davibe commented Oct 21, 2016

Thank you for helping my neurons spin. I think i can close this now :)

@davibe davibe closed this as completed Oct 21, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants