-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore.js
69 lines (59 loc) · 1.58 KB
/
store.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import * as React from 'react';
import characters from './characters'
/**
* If you want to share data between multiple root components, you'll need a
* global store like Redux. This is similar to building a web app where you
* want to synchronize data between a sidebar and a main view - just extended
* into three dimensions.
* To simplify this sample, we implement a trivial Redux-like store that will
* ensure all of our elements are synchronized.
*/
const State = {
characterID: 0,
characterDetails: characters[0]
};
const listeners = new Set();
function updateComponents() {
for (const cb of listeners.values()) {
cb()
}
}
export function initialize() {
State.characterID = 0
State.characterDetails = characters[0]
updateComponents()
}
export function setCharacter(value) {
State.characterID = value
State.characterDetails = characters[value]
updateComponents();
}
export function connect(Component) {
return class Wrapper extends React.Component {
state = {
characterID: State.characterID,
characterDetails: State.characterDetails,
};
_listener = () => {
this.setState({
characterID: State.characterID,
characterDetails: State.characterDetails,
});
};
componentDidMount() {
listeners.add(this._listener);
}
componentWillUnmount() {
listeners.delete(this._listener);
}
render() {
return (
<Component
{...this.props}
characterID={this.state.characterID}
characterDetails={this.state.characterDetails}
/>
);
}
};
}