Skip to content

Instantly share code, notes, and snippets.

@selbekk
Created July 12, 2018 07:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save selbekk/5b9dd8a3737599dceb681ec081f12a1c to your computer and use it in GitHub Desktop.
Save selbekk/5b9dd8a3737599dceb681ec081f12a1c to your computer and use it in GitHub Desktop.
An API state machine HOC
// @flow
import * as React from 'react';
const states = {
IDLE: 'idle',
PENDING: 'pending',
ERROR: 'error',
SUCCESS: 'success',
};
type State = {
currentState: $Values<typeof states>,
}
const withApiState = (TargetComponent: React.ComponentType<{}>): React.ComponentType<{}> => {
class WithApiState extends React.Component<{}, State> {
state = {
currentState: states.IDLE,
};
stateMachine = {
isIdle: () => this.state.currentState === states.IDLE,
isPending: () => this.state.currentState === states.PENDING,
isSuccess: () => this.state.currentState === states.SUCCESS,
isError: () => this.state.currentState === states.ERROR,
setIdle: () => this.setState({ currentState: states.IDLE }),
setPending: () => this.setState({ currentState: states.PENDING }),
setSuccess: () => this.setState({ currentState: states.SUCCESS }),
setError: () => this.setState({ currentState: states.ERROR }),
};
render() {
return (
<TargetComponent {...this.props} apiState={this.stateMachine} />
);
}
}
const targetName = TargetComponent.displayName || TargetComponent.name;
WithApiState.displayName = `withApiState(${targetName})`;
return WithApiState;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment