How to pass variables to a GraphQL query?

前端 未结 3 1455
名媛妹妹
名媛妹妹 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:27

    So far, I know two possible approaches to this.

    The first one is already stated in the question. The variables are at the same time the props of the ProfileWithData. So you need to find a way to change the props and rerender the component. This is usually achieved with a parent component. So usually you do not change the variables inside of ProfileWithData. This component should be used only for display purposes. However, this does not say that it can't be done. You can pass the methods of your parent component to the child in order to manipulate the state of the parent. This will rerender both components and render the ProfileWithData with new props/variables.

    The second approach is to query from the inside of the ProfileWithData component. You can then manipulate the variables from the inside of the component with the state. A method to do this can be found here

    You can do it by passing a reference to Apollo Client using the withApollo higher-order-component, as documented here: http://dev.apollodata.com/react/higher-order-components.html#withApollo

    Then, you can call client.query on the passed in object, like so:

     class MyComponent extends React.Component {
          runQuery() {
            this.props.client.query({
              query: gql`...`,
              variables: { ... },
            });
          }
    
          render() { ... }
        }
    
        withApollo(MyComponent);
    

提交回复
热议问题