File tree Expand file tree Collapse file tree 2 files changed +41
-9
lines changed Expand file tree Collapse file tree 2 files changed +41
-9
lines changed Original file line number Diff line number Diff line change @@ -10,22 +10,27 @@ class Subscriber extends React.Component {
10
10
static propTypes = {
11
11
channel : PropTypes . string . isRequired ,
12
12
children : PropTypes . func ,
13
+ quiet : PropTypes . bool
14
+ }
15
+
16
+ static defaultProps = {
17
+ quiet : false
13
18
}
14
19
15
20
static contextTypes = {
16
21
broadcasts : PropTypes . object
17
22
}
18
23
19
24
state = {
20
- value : null
25
+ value : undefined
21
26
}
22
27
23
28
getBroadcast ( ) {
24
29
const broadcasts = this . context . broadcasts || { }
25
30
const broadcast = broadcasts [ this . props . channel ]
26
31
27
32
invariant (
28
- broadcast ,
33
+ this . props . quiet || broadcast ,
29
34
'<Subscriber channel="%s"> must be rendered in the context of a <Broadcast channel="%s">' ,
30
35
this . props . channel ,
31
36
this . props . channel
@@ -35,19 +40,27 @@ class Subscriber extends React.Component {
35
40
}
36
41
37
42
componentWillMount ( ) {
38
- this . setState ( {
39
- value : this . getBroadcast ( ) . getState ( )
40
- } )
43
+ const broadcast = this . getBroadcast ( )
44
+
45
+ if ( broadcast ) {
46
+ this . setState ( {
47
+ value : broadcast . getState ( )
48
+ } )
49
+ }
41
50
}
42
51
43
52
componentDidMount ( ) {
44
- this . unsubscribe = this . getBroadcast ( ) . subscribe ( value => {
45
- this . setState ( { value } )
46
- } )
53
+ const broadcast = this . getBroadcast ( )
54
+
55
+ if ( broadcast ) {
56
+ this . unsubscribe = broadcast . subscribe ( value => {
57
+ this . setState ( { value } )
58
+ } )
59
+ }
47
60
}
48
61
49
62
componentWillUnmount ( ) {
50
- this . unsubscribe ( )
63
+ if ( this . unsubscribe ) this . unsubscribe ( )
51
64
}
52
65
53
66
render ( ) {
Original file line number Diff line number Diff line change
1
+ import React from "react"
2
+ import ReactDOMServer from "react-dom/server"
3
+ import Subscriber from "../Subscriber"
4
+
5
+ describe ( "A <Subscriber>" , ( ) => {
6
+ it ( "throws an invariant when it is not rendered in the context of a <Broadcast>" , ( ) => {
7
+ expect ( ( ) => {
8
+ ReactDOMServer . renderToStaticMarkup ( < Subscriber channel = "cupcakes" /> )
9
+ } ) . toThrow ( )
10
+ } )
11
+
12
+ describe ( "with quiet=true" , ( ) => {
13
+ it ( "does not throw when it is not rendered in the context of a <Broadcast>" , ( ) => {
14
+ expect ( ( ) => {
15
+ ReactDOMServer . renderToStaticMarkup ( < Subscriber quiet channel = "cupcakes" /> )
16
+ } ) . not . toThrow ( )
17
+ } )
18
+ } )
19
+ } )
You can’t perform that action at this time.
0 commit comments