1
votes

I am using Apollo to create a component. Once the query completes, I need to call some async functions to generate some data that will be rendered inside the component. How can I do this?

Here is some code:

const GET_LOGGED_IN_USER = gql`
  query User($address: String!) {
    member(id: $address) {
      id
    }
  }
`;
class ProposalListView extends React.Component {
  render() {
    let loggedUser = JSON.parse(localStorage.getItem("loggedUser"));
    return (
      <Query query={GET_LOGGED_IN_USER} variables={{ address: loggedUser.address }}>
        {({ loading, error, data }) => {
          if (loading) return "Loading...";
          if (error) throw new Error(`Error!: ${error}`);
          // need to call async function here using data.member.id
          return (
            <div>{resultOfAsyncFunction}</div>
          );
        }}
      </Query>
    );
  }
}

I've tried a few things. I tried making the callback function async (i.e. async ({ loading, error, data }) => {...} but that gave an error.

I also tried adding setState({...}) into the callback and setting the state of the component using the query, but that hit a stack overflow error.

What is the right way to do this?

1
you have an onComplete prop and to that you can pass a function and run the async task thereDhaval Chheda

1 Answers

2
votes

Take a look at the Apollo docs, specifically the ones for the Query component you're using to make your GraphQL query:

https://www.apollographql.com/docs/react/data/queries/#options

There's an onCompleted prop you can pass a method to with the following signature:

<Query
  ...
  onCompleted={(data) => {
    // Call setState() here
  }}
/>

That should get you going.