Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Apollo, don't run query on component load

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.

  1. 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.

  2. I end up having to do some fancy checking in componentWillReceiveProps to prevent loading the query multiple times.

    • I can't use the skip option on the query as this prevents re-fetch function from being passed in.

Short of my sidestepping the HOC all together and manually running the queries through apollo directly, how can I solve this?

like image 633
Justin Avatar asked Aug 04 '17 16:08

Justin


2 Answers

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

like image 158
Justin Avatar answered Oct 13 '22 11:10

Justin


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 },
  },
});
like image 6
Daniel Rearden Avatar answered Oct 13 '22 11:10

Daniel Rearden