Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

refetchQueries onComplete callback

Is it possible to add a callback function to be called when refetchQueries is completed? The problem is that i do not want to let the refetching after a mutation happen in the background as it may confuse users if data does not update immediately and then suddenly updates out of the blue. A submit function could look like this:

async submit(values) {
  this.setState({ submitting: true })
  validateUrl(values.url).then((response:Response) => {
    response.json().then((data) => {
      if (data.length > 0) {
        this.onError("Invalid url")
        this.setState({ submitting: false })
      } else {
        this.props.mutate({
          variables: values,
          refetchQueries: [{ query: LinksQuery}]
        }).then(() => {
          this.props.navigation.pop(2)
          this.props.navigation.state.params.showSuccessFeedback()
          this.setState({ submitting: false })
        });
      }
    });
  })
}

But i don't want to navigate back before the refetch of the LinksQuery is completed.

One solution is to add the Query to the Component using the graphql()-decorator, and then use refetch() which returns a promise. But it would be much cleaner to have it in the refetchQueries option. Especially if several queries should be refetched.

The version of react-apollo is 1.4.15, but i might be willing to upgrade to react-apollo 2.* if it could solve the problem

like image 565
TamRock Avatar asked Jun 06 '18 09:06

TamRock


1 Answers

Per the documentation, we have awaitRefetchQueries:

Queries refetched as part of refetchQueries are handled asynchronously, and are not waited on before the mutation is completed (resolved). Setting this to true will make sure refetched queries are completed before the mutation is considered done. false by default.

So, what you need to do is to set awaitRefetchQueries equal to True inside the object of the mutate function.

async submit(values) {
  this.setState({ submitting: true })
  validateUrl(values.url).then((response:Response) => {
    response.json().then((data) => {
      if (data.length > 0) {
        this.onError("Invalid url")
        this.setState({ submitting: false })
      } else {
        this.props.mutate({
          variables: values,
          refetchQueries: [{ query: LinksQuery}],
          awaitRefetchQueries: true
        }).then(() => {
          this.props.navigation.pop(2)
          this.props.navigation.state.params.showSuccessFeedback()
          this.setState({ submitting: false })
        });
      }
    });
  })
}

I also just came up with the same problem and this worked for me. Hope it helps!

like image 88
Anh Pham Avatar answered Oct 03 '22 07:10

Anh Pham