How to pass variables to a GraphQL query?

前端 未结 3 1464
名媛妹妹
名媛妹妹 2021-02-08 03:57

Lets assume I have the following GraphQL query in React-Apollo

const CurrentUserForLayout = gql`
  query CurrentUserForLayout($avatarID: Int!) {
    currentUser          


        
3条回答
  •  天涯浪人
    2021-02-08 04:22

    Your ProfileWithData component does a good job of rendering the avatar of a certain user. It's not the responsiblity of this component to manage changes of the currently displayed avatar component.

    One way is to add a new prop avatarId that gets passed down from the parent component. Then you would need to write this:

    graphql(CurrentUserForLayout, {
      options: (ownProps) => ({
        variables: {
          id: ownProps.avatarId
        }
      })
    })(Profile);
    

    If you are familiar with react-router, another approach would be to use the route parameters to determine the avatar id. You would need to adjust the call of graphql like this:

    graphql(CurrentUserForLayout, {
      options: (ownProps) => ({
        variables: {
          id: ownProps.params.avatarId
        }
      })
    })(Profile);
    

    To read more about the usage of query variables like this, you can check the React Track of Learn Apollo.

提交回复
热议问题