Intrepid Diamond
Intrepid Diamond

Reputation: 482

How to call setState in Apollo Query Render Props?

I'm trying to combine setState and Apollo Query to create an error at a top level component. I'm actually using React Context, but this gets the same point across.

setError = () => this.setState({ isError: true });

render() {
  return (
   this.state.isError ? <CustomError /> : (
   <Query>
     {({ loading, error, data }) => {

       // first error check
       if (error) { 
         this.setError();
         // this all works if I return <div /> right here, but that's kinda bad
       }
       // I also want to set an error in a child component
       <VeryComplicatedComponentThatCantBeInThisFile setError={this.setError}>
     })
   </Query>
   )
  );
}

Anyone know how to best accomplish this?

Upvotes: 1

Views: 1480

Answers (1)

josephj
josephj

Reputation: 339

I had a similar issue on caching form data with render props. Luckily it provides onError and onComplete callbacks so that you can set states there. Note these callbacks won't be triggered while it uses cache.

class MyComponent extends React.Component {
  setError = () => this.setState({ isError: true });
  handleQueryError = error => {
    this.setError();
  };
  handleQueryComplete = data => {
    this.setState({formData: data});    
  };
  render() {
    return (<Query 
      fetchPolicy="network-only"
      onError={this.handleQueryError}
      onComplete={this.handleQueryComplete}>
      {({ loading, error, data }) => {
        return <VeryComplicatedComponentThatCantBeInThisFile isError={this.state.isError}>
      }}
    </Query>);
  }
}

Upvotes: 1

Related Questions