Skip to content

Instantly share code, notes, and snippets.

@itsMapleLeaf
Created January 1, 2019 01:10
Show Gist options
  • Select an option

  • Save itsMapleLeaf/17efa424f6025c8ef88c5657e2998813 to your computer and use it in GitHub Desktop.

Select an option

Save itsMapleLeaf/17efa424f6025c8ef88c5657e2998813 to your computer and use it in GitHub Desktop.
class Container<S> {
setState(newState: Partial<S>) {
// ...
}
}
type CounterState = {
count: number
}
class CounterContainer extends Container<CounterState> {
state = {
count: 0,
}
increment() {
this.setState({ count: this.state.count + 1 })
}
decrement() {
this.setState({ count: this.state.count - 1 })
}
}
class TodoContainer extends Container<{}> {
state = {
todos: [] as { text: string }[],
}
addTodo(text: string) {
this.setState({ todos: [...this.state.todos, { text }] })
}
}
type ContainerClassRecord = {
[name: string]: new (...args: unknown[]) => Container<any>
}
declare function Subscribe<C extends ContainerClassRecord>(props: {
to: C
children: SubscribeRender<C>
}): React.ReactElement<{}>
type SubscribeRender<C extends ContainerClassRecord> = (
containers: { [K in keyof C]: InstanceType<C[K]> },
) => React.ReactNode
const test = (
<Subscribe to={{ counter: CounterContainer, todos: TodoContainer }}>
{({ counter, todos }) => (
<div>
<button onClick={() => counter.decrement()}>-</button>
<span>{counter.state.count}</span>
<button onClick={() => counter.increment()}>+</button>
<ul>
{todos.state.todos.map((todo) => (
<li>{todo.text}</li>
))}
</ul>
</div>
)}
</Subscribe>
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment