Skip to content

Commit fa7d964

Browse files
Martin Spencermspae
Martin Spencer
authored andcommitted
feat(core): added resourceData prop to prevent fetches
fix #5
1 parent b059cf3 commit fa7d964

File tree

1 file changed

+43
-7
lines changed

1 file changed

+43
-7
lines changed

packages/core/src/components/Query.js

+43-7
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import React, { PureComponent } from "react";
22
import PropTypes from "prop-types";
3-
import { readEndpoint } from "redux-json-api";
3+
import { readEndpoint, hydrateStore } from "redux-json-api";
44
import { connect } from "react-redux";
55
import { DataSet } from ".";
66
import { selectApiIsReady } from "../selectors";
@@ -17,12 +17,14 @@ export class QueryPresentational extends PureComponent {
1717
PropTypes.string,
1818
PropTypes.arrayOf(PropTypes.string)
1919
]),
20-
apiIsReady: PropTypes.bool
20+
apiIsReady: PropTypes.bool,
21+
resourceData: PropTypes.object
2122
};
2223

2324
static defaultProps = {
2425
uuid: null,
25-
apiIsReady: false
26+
apiIsReady: false,
27+
resourceData: null
2628
};
2729

2830
state = {
@@ -31,19 +33,53 @@ export class QueryPresentational extends PureComponent {
3133
};
3234

3335
componentDidMount() {
34-
const { apiIsReady } = this.props;
36+
const { apiIsReady, resourceData } = this.props;
37+
if (resourceData) {
38+
return this.hydrateStore();
39+
}
3540
if (apiIsReady) {
3641
this.fetchData();
3742
}
3843
}
3944

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) {
4354
this.fetchData();
4455
}
4556
}
4657

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+
4783
/**
4884
* Fetch the actual data from the API
4985
*

0 commit comments

Comments
 (0)