Created
February 2, 2018 06:46
-
-
Save marcins/ed0a4e013029937ddb043e8ac7f1709f to your computer and use it in GitHub Desktop.
Flow typing for passing Unstated Container as props?
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
// @flow | |
import React from "react"; | |
import { render } from "react-dom"; | |
import { Provider, Subscribe, Container } from "unstated"; | |
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 }); | |
} | |
} | |
function Counter(props: /* { counter: ??? } */) { | |
const counter = props.counter; | |
return ( | |
<div> | |
<button onClick={() => counter.decrement()}>-</button> | |
<span>{counter.state.count}</span> | |
<button onClick={() => counter.increment()}>+</button> | |
</div> | |
); | |
} | |
// What's the type of props.counter? | |
// Should CounterContainer export a CounterContainerType? | |
// Should the functions be on state? | |
// Something else?? | |
// | |
type CounterContainerType = { | |
state: CounterState, | |
increment: () => void, | |
decrement: () => void, | |
} | |
// | |
function ConnectedCounter() { | |
<Subscribe to={[CounterContainer]}> | |
{counter => <Counter counter={counter} />} | |
</Subscribe>; | |
} | |
render( | |
<Provider> | |
<Counter /> | |
</Provider>, | |
window.simple | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment