Last active
March 4, 2019 20:38
-
-
Save gaganjakhotiya/acdc91876eaad0a7c222db73d0b8d827 to your computer and use it in GitHub Desktop.
State management for React using inheritance
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 React from "react"; | |
import * as Flux from "./Flux"; | |
export default class App extends Flux.Component { | |
getState(data) { | |
return { name: data.name }; | |
} | |
componentWillMount() { | |
setTimeout(() => Flux.Component.__update_context__({ name: "World" }), 2000); // Async response | |
} | |
render() { | |
return <Text>Hello, {this.state.name}!</Text> | |
} | |
} |
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 React from "react"; | |
type ContextData = { [key: string]: any }; // Should be more specific | |
export abstract class Component<P = {}, S = {}> extends React.Component<P, S> { | |
abstract getState(context: ContextData): S; | |
abstract render(): React.ReactNode; | |
private static listeners: { [key: string]: () => void } = {}; | |
private static data?: ContextData; | |
private id: string; | |
constructor(props: P) { | |
super(props); | |
this.id = String(new Date().getTime()); | |
this.state = this.getState(Component.data); | |
let _render = this.render.bind(this); | |
let _componentDidMount = this.componentDidMount.bind(this); | |
let _componentWillunmount = this.componentWillUnmount.bind(this); | |
this.componentDidMount = () => { | |
Component.listeners[this.id] = this.__update_component__.bind(this); | |
_componentDidMount(); | |
}; | |
this.render = () => | |
Component.__context_ready__() ? _render() : <React.Fragment />; | |
this.componentWillUnmount = () => { | |
delete Component.listeners[this.id]; | |
_componentWillunmount(); | |
}; | |
} | |
public static __context_ready__() { | |
return Component.data !== undefined; | |
} | |
public static __update_context__(data: ContextData) { | |
Component.data = data; | |
Object.keys(Component.listeners).forEach(id => Component.listeners[id]()); | |
} | |
private __update_component__ = () => { | |
Component.__context_ready__() && | |
this.setState(this.getState(Component.data)); | |
}; | |
componentDidMount() {} | |
componentWillUnmount() {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment