Search code examples
reactjsreact-nativereact-reduxredux-thunk

return promise from thunk


I'm trying to use my first thunk in redux-thunk:

getting redux-thunk into my app which already uses redux-observable:

import thunk from 'redux-thunk'

export const store = createStore(
  rootReducer,
  vepo,
  composeWithDevTools(applyMiddleware(createEpicMiddleware(rootEpic), thunk))
)

Using it like so:

Action creator:

export const updateShowProductIsVeganModal = (payload: boolean) => {
  return function (dispatch) {
    return new Promise((resolve, reject) => {
      dispatch({
        type: 'UPDATE_INSPECTION_SHOW_PRODUCT_IS_VEGAN_MODAL',
        payload
      })
      resolve()
    })
  }
}

Then I have this component (It's much bigger, I've stripped it down for this question):

const veganPress = (props, refs) => {
  props.updateShowProductIsVeganModal(true).then(() => {
    console.log("plz work")
    refs.toast.show('hello world!')
  })
}

class ProductDetailsView extends Component<any, State> {
  render = () => {
    return (
       <Button onPress={() => veganPress(this.props, this.refs)}>
       <Toast ref="toast"/>
    )}
}

const mapDispatchToProps = (dispatch: Dispatch<*>): any => ({
  updateShowProductIsVeganModal: (show: boolean) => {
    dispatch(updateShowProductIsVeganModal(show))
  }
})

const view = connect(
  mapStateToProps,
  mapDispatchToProps
)(ProductDetailsView)

I get the error:

ExceptionsManager.js:63 Cannot read property 'then' of undefined

It is referring to the .then inside veganPress()

How can return a promise that can use .then in the way I am trying to do it?


Solution

  • updateShowProductIsVeganModal doesnt return promise. Change it to

    const mapDispatchToProps = (dispatch: Dispatch<*>): any => ({
      updateShowProductIsVeganModal: (show: boolean) => {
        return dispatch(updateShowProductIsVeganModal(show))
      }
    })