Ad

How Can I Call The Function Clinet.query Through The Function?

- 1 answer

I would like to call the client.query through function however it does not work. For example, when the user click a button, I want to call a function named handleClick to get the query The following is an example to how call client.query by the function

class DelayedQuery extends Component {
    state = { dog: null };

    onDogFetched = dog => this.setState(() => ({ dog }));

    handleClick = (client) => {  //<-------I call the function
        async () => {
            const { data } = await client.query({
                query: GET_DOG_PHOTO,
                variables: { breed: "bulldog" }
            });
            this.onDogFetched(data.dog);
        }
    }

    render() {
        return (
            <ApolloConsumer>
                {client => (
                    <div>
                        {this.state.dog && <img src={this.state.dog.displayImage} />}
                        <button onClick={()=>this.handleClick(client) } > Click me! </button> // <-------I call handleClick 
                    </div>
                )}
            </ApolloConsumer>
        );
    }
}

How can I call the function clinet.query through the function?

Ad

Answer

I solve the problem by make the handleClick async

class DelayedQuery extends Component {
    state = { dog: null };

    onDogFetched = dog => this.setState(() => ({ dog }));

    handleClick = async (client) => {
            const { data } = await client.query({
                query: GET_DOG_PHOTO,
                variables: { breed: "bulldog" }
            });
            this.onDogFetched(data.dog);
    }

    render() {
        return (
            <ApolloConsumer>
                {client => (
                    <div>
                        {this.state.dog && <img src={this.state.dog.displayImage} />}
                        <button onClick={()=>this.handleClick(client) } > Click me! </button>
                    </div>
                )}
            </ApolloConsumer>
        );
    }
}
Ad
source: stackoverflow.com
Ad