Skip to content

Instantly share code, notes, and snippets.

@oukayuka
Last active August 6, 2020 12:39
Show Gist options
  • Save oukayuka/68f87b5bdb63467bdf88b85c0a561a8d to your computer and use it in GitHub Desktop.
Save oukayuka/68f87b5bdb63467bdf88b85c0a561a8d to your computer and use it in GitHub Desktop.
Recompose withStateHandlers with TypeScript
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);
@lkostrowski
Copy link

Hi, have you figured out example with withHandlers ?

@ArtemKorchunov
Copy link

ArtemKorchunov commented Apr 22, 2019

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