I'm using the awesome https://github.com/apollographql/react-apollo library and I'm trying to see if there is a better convention to load data into components than how I'm doing it now.
I've set up my components to with the apollo HOC to load data into my components, like so:
const mainQuery = gql`
query currentProfileData($userId:String, $communityId:String!){
created: communities(id:$communityId) {
opportunities{
submittedDate
approvalDate
status
opportunity{
id
}
}
}
}
`;
const mainQueryOptions = {
options: {
variables: { userId: '_', communityId: '_' },
},
};
const ComponentWithData = compose(
graphql(mainQuery, mainQueryOptions),
)(Component);
This setup works great, but with some problems.
I end up with queries that always run twice, as I need to pass props to apollo refetch for the query. I also have to pass in some dummy data (aka the "_") to prevent useless data fetching.
I end up having to do some fancy checking in componentWillReceiveProps to prevent loading the query multiple times.
Short of my sidestepping the HOC all together and manually running the queries through apollo directly, how can I solve this?
Just a little follow up.
With the insight of @daniel, I was able to solve my 2 primary problems, run queries with props, and skipping the query conditionally until it's ready. I just wanted to post my final code result. As you can set functions for both of these options, it helps a ton.
const mainQueryOptions = {
skip: ({ community: { id: communityId } }) => !communityId,
options: ({ community: { id: communityId }, user: { id: userId = '_' } }) => ({
variables: { userId, communityId },
}),
};
You can find more info here on the apollo api page: http://dev.apollodata.com/react/api-graphql.html#graphql
If you're utilizing your component's props as the variables used in the refetch
call, there is in fact a cleaner approach. The options
property can actually be a function that takes your component's props. This lets you derive your variables from the props passed to your component. It would look something like this:
const mainQueryOptions = {
options: ({ userId, communityId }) => ({
variables: { userId, communityId },
},
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With