Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Oct 9, 2018

Hi, have you figured out example with withHandlers ?

@ArtemKorchunov

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.