Skip to content

Instantly share code, notes, and snippets.

@Avol-V
Created April 12, 2017 11:36
Show Gist options
  • Save Avol-V/1af4748f4b0774a999311c92b6dc1631 to your computer and use it in GitHub Desktop.
Save Avol-V/1af4748f4b0774a999311c92b6dc1631 to your computer and use it in GitHub Desktop.
small-redux-tests
import {Component} from 'preact';
import {Action, Store, Unsubscribe} from 'small-redux';
/**
* Create Class of Component with subscription to Store changes.
*
* @template TState State object type.
* @template TAction Action object type.
* @param store Redux store object.
* @returns Abstract Class of Component with subscription to Store changes.
*/
function createSubscribedComponent<TState, TAction extends Action>(
store: Store<TState, TAction>,
)
{
/**
* Abstract Class of Component with subscription to Store changes.
*
* @template PropsType Component properties.
* @template StateType Component state.
*/
abstract class SubscribedComponent<PropsType, StateType>
extends Component<PropsType, StateType>
{
/**
* A function to remove this change listener.
*/
protected unsubscribe: Unsubscribe | undefined;
/**
* Abstract Class of Component with subscription to Store changes.
*
* @param props Component properties.
*/
public constructor( props: PropsType )
{
super( props );
this.storeStateChanged( store.getState() );
}
/**
* Subscribe when added to DOM.
*/
public componentDidMount(): void
{
this.unsubscribe = store.subscribe(
() => this.storeStateChanged( store.getState() ),
);
}
/**
* Unsubscribe before removing from DOM.
*/
public componentWillUnmount(): void
{
if ( this.unsubscribe )
{
this.unsubscribe();
this.unsubscribe = undefined;
}
}
/**
* Handle Store changes.
*
* @param state The current state tree of your application.
*/
protected abstract storeStateChanged( state: TState ): void;
}
return SubscribedComponent;
}
/**
* Module.
*/
export {
createSubscribedComponent as default,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment