redux-utilities / redux-promise

FSA-compliant promise middleware for Redux.
MIT License
2.67k stars 134 forks source link

Promise resolves before actions are dispatched #42

Closed ChrisPenner closed 2 years ago

ChrisPenner commented 7 years ago

Hey folks! The library looks cool!

I'm running into a little snag with how I'm using it though, wondering if you can help me out.

inside createActions I define an action like this:

createActions({
  LOAD_STUFF: fetch(<url>).then(resp => resp.json())
})

Which in my understanding means that dispatch(loadStuff()) should resolve the promise and dispatch the following action:

{
  type: 'LOAD_STUFF',
  payload: <response json>
}

This all works, but in my ui code I'm calling it within React-Router's onEnter hook like this:

const onEnter = (nextState, replace, callback) => {
  dispatch(loadStuff()).payload.then(() => callback())
}

Note that the page will load as soon as callback is called and so I need the data to be loaded. In my case however it seems that the promise is resolving as soon as the fetch is complete, but BEFORE the dispatch is complete, and for that reason my app is loading the page before the data is in my state.

Have any tips for this? Thanks!

joshka commented 7 years ago

Hiya, It looks pretty much like you're calling fetch() as soon as you call createAction. I'm guessing you probably want something more like:

createActions({
  LOAD_STUFF: () => fetch(<url>).then(resp => resp.json())
})