-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathComparison.js
102 lines (93 loc) · 2.6 KB
/
Comparison.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import React from "react"
//------------------Written as a class---------------------//
class Farm extends React.Component {
constructor(props) {
super(props)
this.state = {
tools: ["hammer", "scythe", "sickle"]
}
}
componentDidMount() {
fetch("/tools")
.then(({ body: { tools } }) => this.setState(tools))
.catch(err =>
console.log("Oh no, your tools got lost. Here's why: ", err)
)
}
shouldComponentUpdate(nextProps, nextState) {
return nextState.tools !== this.state.tools
}
render() {
const { tools } = this.state
const { someProp, anotherProp } = this.props
if (!(tools && tools.length)) {
return null
}
return (
<div>
Here are all the tools in the farm:
<ul>
{tools.map((tool, index) => (
<li key={index}> {tool} </li>
))}
</ul>
{someProp} - {anotherProp}
</div>
)
}
}
// And now the exact same thing, written functionally.
//---------------------------------------------------------------//
// Only the 'view' logic.
const BaseFarm = ({ someProp, anotherProp, tools }) => (
<div>
Here are all the tools in the farm:
<ul>
{tools.map((tool, index) => (
<li key={index}> {tool} </li>
))}
</ul>
{someProp} - {anotherProp}
</div>
)
// All the 'other' stuff.
const didMount = ({ setTools }) =>
fetch("/tools")
.then(({ body: { tools } }) => setTools(tools))
.catch(err => console.log("Oh no, your tools got lost. Here's why: ", err))
const shouldNotRender = ({ tools }) => !(tools && tools.length)
const Farm = withState("tools", "setTools", ["hammer", "scythe", "sickle"])(
// N.B: lifecycle isn't from recompose
lifecycle({ didMount })(
branch(shouldNotRender, renderNothing)(
onlyUpdateForKeys(["tools"])(BaseFarm)
)
)
)
//Or better:
const Farm = compose(
withState("tools", "setTools", ["hammer", "scythe", "sickle"]),
lifecycle({ didMount }),
branch(shouldNotRender, renderNothing),
onlyUpdateForKeys(["tools"])
)(BaseFarm)
// Alternatively.
const enhance = compose(
withState("tools", "setTools", ["hammer", "scythe", "sickle"]),
lifecycle({ didMount }),
branch(shouldNotRender, renderNothing),
onlyUpdateForKeys(["tools"])
)
// enhance is a HOC, composed of a few other HOCs.
// It takes a component (BaseFarm) and returns Farm.
const Farm = enhance(({ someProp, anotherProp, tools }) => (
<div>
Here are all the tools in the farm:
<ul>
{tools.map((tool, index) => (
<li key={index}> {tool} </li>
))}
</ul>
{someProp} - {anotherProp}
</div>
))