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.