React Apollo - Make Multiple Queries

2019-03-09 01:48发布

I have a queries file that looks like this:

import {gql} from 'react-apollo';

const queries = {
  getApps: gql`
    {
      apps {
        id
        name
      }
    }
  `,
  getSubjects: gql`
    {
      subjects {
        id
        name
      }
    }
  `
};

export default queries;

I then import this file to my React component:

import React, {Component} from 'react'
import queries from './queries'

class Test extends Component {
...
}

export default graphql(queries.getSubjects)(graphql(queries.getApps)(Test));

This will only get data for one of the queries (getApps) and not both. If I do one at a time so that it looks like this:

export default graphql(queries.getSubjects)(Test);

then it works but I don't have my other query. Yes, I have tested both separately and they work. How do I get it so that both queries show up in my props.data?

7条回答
贪生不怕死
2楼-- · 2019-03-09 02:47

A query and mutation using react-apollo's compose

Things that I've concluded:

  1. Compose runs it's queries from the bottom up.
  2. Queries are run automatically, you don't have to call them, but Mutations you do.
  3. It's apparent that the Apollo team wants everyone to use the Query component rather than compose. Therefore, I think it would be wise to use they Query Component as they suggest because they might deprecate compose later.

Here's the code if you still want to use compose:

import {gql} from 'graphql-tag'
import {graphql, compose} from 'react-apollo'
import React, {Component} from 'react'

const appQuery = gql`
    {
      apps {
        id
        name
      }
    }
  `

const subjectMutation = gql`
    mutation someName($name: String) {
      changeSubjects(name: $name) {
        subject {
          name
        }
      }
    }
  `
};

class Test extends Component {
...

  const MutationResponse = this.props.mutate({
    variables: {
      name: "some name"
    }
  })

  const QueryResponse = this.props.data.appQuery

...
}

export default compose(
  graphql(appQuery),
  graphql(subjectMutation) 
)(Test));
查看更多
登录 后发表回答