1
1
import React , { PureComponent } from "react" ;
2
2
import PropTypes from "prop-types" ;
3
- import { readEndpoint } from "redux-json-api" ;
3
+ import { readEndpoint , hydrateStore } from "redux-json-api" ;
4
4
import { connect } from "react-redux" ;
5
5
import { DataSet } from "." ;
6
6
import { selectApiIsReady } from "../selectors" ;
@@ -17,12 +17,14 @@ export class QueryPresentational extends PureComponent {
17
17
PropTypes . string ,
18
18
PropTypes . arrayOf ( PropTypes . string )
19
19
] ) ,
20
- apiIsReady : PropTypes . bool
20
+ apiIsReady : PropTypes . bool ,
21
+ resourceData : PropTypes . object
21
22
} ;
22
23
23
24
static defaultProps = {
24
25
uuid : null ,
25
- apiIsReady : false
26
+ apiIsReady : false ,
27
+ resourceData : null
26
28
} ;
27
29
28
30
state = {
@@ -31,19 +33,53 @@ export class QueryPresentational extends PureComponent {
31
33
} ;
32
34
33
35
componentDidMount ( ) {
34
- const { apiIsReady } = this . props ;
36
+ const { apiIsReady, resourceData } = this . props ;
37
+ if ( resourceData ) {
38
+ return this . hydrateStore ( ) ;
39
+ }
35
40
if ( apiIsReady ) {
36
41
this . fetchData ( ) ;
37
42
}
38
43
}
39
44
40
- componentDidUpdate ( { apiIsReady : apiWasReady } ) {
41
- const { apiIsReady } = this . props ;
42
- if ( ! apiWasReady && apiIsReady ) {
45
+ componentDidUpdate ( {
46
+ apiIsReady : apiWasReady ,
47
+ resourceData : prevResourceData
48
+ } ) {
49
+ const { apiIsReady, resourceData } = this . props ;
50
+ if ( prevResourceData !== resourceData ) {
51
+ return this . hydrateStore ( ) ;
52
+ }
53
+ if ( ! prevResourceData && ! resourceData && ! apiWasReady && apiIsReady ) {
43
54
this . fetchData ( ) ;
44
55
}
45
56
}
46
57
58
+ hydrateStore = async ( ) => {
59
+ try {
60
+ const { resourceData, dispatch } = this . props ;
61
+ await this . _setState ( {
62
+ loading : true
63
+ } ) ;
64
+ await dispatch ( hydrateStore ( { data : resourceData } ) ) ;
65
+ const resourceIds = Array . isArray ( resourceData )
66
+ ? resourceData . map ( entity => ( {
67
+ type : entity . type ,
68
+ id : entity . id
69
+ } ) )
70
+ : { type : resourceData . type , id : resourceData . id } ;
71
+
72
+ await this . _setState ( {
73
+ loading : false ,
74
+ resourceIds
75
+ } ) ;
76
+ } catch ( e ) {
77
+ // eslint-disable-next-line no-console
78
+ console . error ( e ) ;
79
+ await this . _setState ( { loading : false , error : e } ) ;
80
+ }
81
+ } ;
82
+
47
83
/**
48
84
* Fetch the actual data from the API
49
85
*
0 commit comments