-
-
Save Avol-V/1af4748f4b0774a999311c92b6dc1631 to your computer and use it in GitHub Desktop.
small-redux-tests
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 {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