React-apollo: How to pass dynamic route parameter to query

Created on 12 Feb 2017  路  4Comments  路  Source: apollographql/react-apollo

How can i pass the parameter from my dynamic route to the query of the container that i render on the route?

Having the following route:

      path: '/company/:companyId',
      name: 'companyPage',
      getComponent(nextState, cb) {
        const importModules = Promise.all([
          import('containers/CompanyPage'),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([component]) => {
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      }

How can i pass the companyId parameter to my container to rerender if the route changes.
I know i can access it within the route-definition using nextState.params.companyId.

In a redux setting i was doing:
store.dispatch(actions.getCompany(nextState.params.companyId));... Don't know how to do this in apollo.

In containers/CompanyPage i defined the graphql-query as follows:
How do i specify options to make it work?

const withData = graphql(COMPANY_QUERY, {
  options: ({ companyId }) => ({ variables: { companyId } }),
  props: ({ data: { loading, companyByCompanyId, error } }) => ({
    loading,
    error,
    company: companyByCompanyId,
  }),
});
export default withData(CompanyPage);

Most helpful comment

Got it: react-router exposes this parameter via ownProps.params.companyId

const withData = graphql(COMPANY_QUERY, {
  options: (ownProps) => ({ variables: { companyId: ownProps.params.companyId } }),
  props: ({ data: { loading, companyByCompanyId, error } }) => ({
    loading,
    error,
    company: companyByCompanyId,
  }),
});

All 4 comments

Got it: react-router exposes this parameter via ownProps.params.companyId

const withData = graphql(COMPANY_QUERY, {
  options: (ownProps) => ({ variables: { companyId: ownProps.params.companyId } }),
  props: ({ data: { loading, companyByCompanyId, error } }) => ({
    loading,
    error,
    company: companyByCompanyId,
  }),
});

How do we input param to this withData?

Does your nested page persist? Not with a refresh click but with actually typing the URL and pressing enter.

how to make COMPANY_QUERY available via props?

Was this page helpful?
0 / 5 - 0 ratings