简体   繁体   中英

recompose withHandlers … asynchronously?

Is is possible/safe to use withHandlers with promises? Ex.:

withHandlers({
    onChange: props => event => {
      props.callAPI(props.data)
        .then(data => props.updateData(data))
    },
...

Thanks!

After some tests I realized that it's working pretty well. Recompose rocks for building with pure components.

This is perfectly valid and working pretty well.

const enhWithHandlers = withHandlers({
  loginUserMutation: props => args => {
    props.updateMutationState(loading: true, error: null });
    props.loginUser(args)
      .then(() =>
        props.updateMutationState({loading: false, error: null }))
      .catch(err =>
        props.updateMutationState({ loading: false, error: err }));
  }
},
...
// then compose like
export default compose(
  reduxConnect,
  gqlConnectLogin,
  gqlConnectRegister,
  enhWithState,
  enhWithHandlers
)(UserLoginRegister);

It helps me to overcome lack of ability to reflect results of graphQl mutation with Apollo client to the wrapped component. This handles it perfectly and without the need of side effects in the component itself.

But there are some problems when we use it like this:

compose(
  withState('loginStatus', 'setLoginStatus', {loading: false, error:null}),
  withHandlers({
    loginUserMutation: props => async args => {
      try {
        props.setLoginStatus({loading: true, error: null});
        await props.loginUser(args);
      } catch(error) {
        props.setLoginStatus({...props.loginStatus, error});
      } finally {
        props.setLoginStatus({...props.loginStatus, loading: false});
      }
    }
  })
)

Because the props reference is indeed lost after we await props.loginUser(args) . Then we use it after that is wrong.

We should notice not to use it like above.


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM