Reputation: 1672
react-apollo
provides the ability to convert component props to query variables:
<MyComponentWithData propsForQueryVariables={...} />
But I need start query with variables from wrapped component.
Something like:
class MyComponent extends React.Component {
//...
onReady() {
// should be first request to server
this.props.refetch({
// variables here
})
}
onFilterChanged() {
this.props.refetch({
// new variables here
})
}
}
const MyComponentWithData = graphql(QUERY, {
options: {
waitUntilComponentStartQuery: true
// pollInterval:...
},
props({ data: { items, refetch } }) {
return {
items: items,
refetch: refetch
};
}
})(MyComponent);
UPDATE
QUERY
for MyComponent
looks like
query getItems($filter: JSON!) {
items(filter: $filter) {
id
name
}
}
filter
is not nullable. So the first request should have valid variable filter
, and this variable should be created in wrapped component.
Upvotes: 4
Views: 5009
Reputation: 388
You can pass the parent props to the variables of the initial fetch in the graphql HoC, like this:
ParentComponent.jsx
import ChildComponent from './ChildComponent';
const ParentComponent = () => <ChildComponent filterPropValue="myDefaultFilterValue" />;
export default ParentComponent;
ChildComponent.jsx
class ChildComponent extends React.Component {
refresh() {
this.props.refetch({
filter: 'mynewFilterValue'
});
}
render() {
return (
<div>I am a child component with {this.props.items.length} items.</div>
);
}
}
export default graphql(MyQuery, {
options: (props) => ({
variables: {
filter: props.filterPropValue
}
}),
props: ({ data: { items, error, refetch }) => ({
items,
error,
refetch
})
})(ChildComponent);
Any subsequent refetches with new parameters can then be dealt with via refetch()
.
Upvotes: 4
Reputation: 4097
refetch
accepts a variables
object as argument, see the documentation.
Upvotes: 1