Last active
August 6, 2020 12:39
-
-
Save oukayuka/68f87b5bdb63467bdf88b85c0a561a8d to your computer and use it in GitHub Desktop.
Recompose withStateHandlers with TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react'; | |
import { compose, lifecycle, pure, StateHandler, StateHandlerMap, withStateHandlers } from 'recompose'; | |
import { Message, Transition } from 'semantic-ui-react'; | |
import './FlashMessage.css'; | |
export interface FlashMessageProps { | |
message: string; | |
isWarning?: boolean; | |
} | |
interface StateProps { | |
visible: boolean; | |
} | |
type StateHandlerProps = StateHandlerMap<StateProps> & { | |
display(): StateHandler<StateProps>; | |
erase(): StateHandler<StateProps>; | |
}; | |
type EnhancedFlashMessageProps = | |
FlashMessageProps & | |
StateProps & | |
StateHandlerProps; | |
const FlashMessage: React.SFC<EnhancedFlashMessageProps> = ({ | |
message = '', | |
isWarning = false, | |
visible, | |
erase, | |
}) => ( | |
<> | |
<Transition | |
visible={visible} | |
animation="fade" | |
duration={800} | |
> | |
<Message | |
className="flash-message" | |
positive={!isWarning} | |
negative={isWarning} | |
onDismiss={erase} | |
> | |
{message} | |
</Message> | |
</Transition> | |
</> | |
); | |
export default compose< | |
EnhancedFlashMessageProps, | |
FlashMessageProps | |
>( | |
withStateHandlers< | |
StateProps, | |
StateHandlerProps, | |
FlashMessageProps | |
>( | |
(props) => ({ | |
...props, | |
visible: false, | |
}), | |
{ | |
display: (state, props) => () => ({ | |
visible: true, | |
}), | |
erase: (state, props) => () => ({ | |
visible: false, | |
}), | |
}, | |
), | |
lifecycle<EnhancedFlashMessageProps, {}, {}>({ | |
componentDidMount() { | |
const { message, display, erase } = this.props; | |
if (message) { | |
display(); | |
setTimeout(() => erase(), 3000); | |
} | |
}, | |
}), | |
pure, | |
)(FlashMessage); |
I suppose that there is one mistake with your example
type StateHandlerProps = StateHandlerMap<StateProps> & {
display(): StateHandler<StateProps>;
erase(): StateHandler<StateProps>;
};
It needs to be something like this
type StateHandlerProps = StateHandlerMap<StateProps> & {
display: StateHandler<StateProps>;
erase: StateHandler<StateProps>;
};
I've posted explanation for it there
https://stackoverflow.com/questions/54725408/how-to-resolve-an-error-in-typescript-about-withstatehandlers?answertab=active#tab-top
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, have you figured out example with
withHandlers
?