Multiple Queries/Mutation in Apollo 2.1

后端 未结 6 523
滥情空心
滥情空心 2021-02-05 12:10

I need some help using the new Query and Mutation component in Apollo 2.1, especially with multiple queries and mutations.

I have the following problems:

  1. I
相关标签:
6条回答
  • 2021-02-05 12:35

    Asides from using compose from react-apollo, another great utility library you can check it out is react-adopt. A great small utility lib that helps you to compose multiple render props type components so you don't have a nested hell patterns.

    I have wrote a similar answer that basically covers all your current needs in terms of:

    • How to consume a previous result from your mapper fn via react-adopt
    • Combine multiple Query/Mutations from Composed component via react-adopt

    Here's the detailed answer you're looking for & hopefully can be helpful to solving your problems :)

    0 讨论(0)
  • 2021-02-05 12:45

    I wrote a Medium Post about how to combine Mutation and Query on the same Component. Here is a snippet from the post

    // other import
    import {Query} from “Apollo-graphql”; // new Query Component
    import gql from "graphql-tag";
    import { graphql } from "react-apollo";
    import UserComponent from '../component/UserComponent'; // any component to display query result
    const GET_ALL_USER = gql`
        {
            allUsers: {
                firstname,
                lastname,
                username,
                # other information
            }
        }
    `
    const UPDATE_USER_STATUS = gql`
        mutation UpdateUserStatus($userID: ID!, $status: Int!){
            updateUserState(userID: $userID, status: $status){
                firstname,
                lastname
                username
                # other information
            }
        }
    `
    ExampleComponent extends React.Component{
        onEditInformation = async (user) => {
            const response  = await mutate({
                variables: {userID: user}
            })
        }
    render(){
            return(
                <Query query={GET_ALL_USER}>
                    {({data: { allUsers }}) => {
                        return allusers.map(user => {
                            return (
                                <UserComponent
                                    user={user}
                                    onEdit={() => this.onEditInformation(user)}
                                />
                            )
                        })
                    }}
                </Query>
            )
        }
    }
    export default graphql(UPDATE_USER_STATUS)(ExampleComponent);
    
    0 讨论(0)
  • 2021-02-05 12:46

    For this purpose react-apollo exports a compose function. Using this function you may cleanly use several component enhancers at once. Including multiple graphql(), or even Redux connect() enhancers.

    import { Mutation, compose, graphql } from "react-apollo";
    
    class AddTweet extends Component {
    ....
    ....
    ....
    }
    export default compose(
      graphql(GET_AUTHORS, { name: "getAuthors" }),
      graphql(ADD_TWEET, { name: "addTweet" }),
      connect(...), // incase you are using Redux
    )(AddTweet);
    

    An important note is that compose() executes the last enhancer first and works its way backwards through the list of enhancers.

    One more thing lets say you were using this.props.data now you will get get undefined. just console.log(this.props) and you will see what is happening to props now. You will be having two properties now getAuthors and addTweet. So now it will be this.props.name-in-compose.name-of-type-in-typeDefs i.e. this.props.getAuthors.getUsers. It took me a bit to figure it out.

    0 讨论(0)
  • 2021-02-05 12:46

    In my opinion,

    1. To make a request depends on previous request, you can break that request to children component and pass result of previous request like props to it and do that request.
    2. To use more than one mutation and queries, you can use compose like this

      ...
      @compose(
       graphql(GET_FEEDS_QUERY, {name : 'getFeeds'}),
       graphql(CREATE_NEW_POST, {name: "createNewPost"}),
       graphql(LIKE_POST_MUTATION, { name: "unlikePostMutation"}),
       ...
      )
      class HomeScreen extends Component {
       ...
      }
      
    0 讨论(0)
  • 2021-02-05 12:47

    edit 2019/08/24 from the Apollo docs:

    The new hooks API for Apollo Client is a simpler way to fetch data in your React app without the boilerplate of render prop components and higher-order components (HOC). We recommend using hooks for all new Apollo code going forward.

    original answer: You are supposed to nest them. See this example:

    const NumbersWithData = () => (
      <Query query={QueryOne}>
        {({ loading: loadingOne, data: { one } }) => (
          <Query query={QueryTwo}>
            {({ loading: loadingTwo, data: { two }}) => {
              if (loadingOne || loadingTwo) return <span>loading...</span>
              return <h3>{one} is less than {two}</h3>
            }}
          </Query>
        )}
      </Query>
    );
    

    To help with keeping the nesting manageable, you could check react-adopt. They have an Apollo ToDo App example, where they combine a Query and multiple Mutations.

    0 讨论(0)
  • 2021-02-05 12:48

    Best solution for this

    Simply nest graphql function

    export default graphql(addBookMutation)(graphql(getAuthorsQuery)(AddBook))

    You can refer to this

    Apollo concepts

    0 讨论(0)
提交回复
热议问题