[英]How to call a GraphQL query using Apollo?
I have a simple component:我有一个简单的组件:
import { FC } from 'react';
import './MyComponent.css';
import { useGetHelloQuery, useSendMailQuery } from '../../generated/queries'
interface MyComponentProps {}
const MyComponent: FC<MyComponentProps> = () => {
const { data: hello, loading: isLoading } = useGetHelloQuery();
const { data: sendMail, loading: isMailing } = useSendMailQuery();
if (isLoading || isMailing) {
return (
<div>Loading...</div>
)
}
return (
<>
<div className="MyComponent">
data: {hello?.getHello}
</div>
</>
)
}
export default MyComponent
That calls this resolver:这调用了这个解析器:
// Apollo server resolvers
import { Resolvers } from "../generated/resolvers-types"
import * as mail from "./nodemailer"
export const resolvers: Resolvers = {
Query: {
getHello() {
return 'hello'
},
sendMail() {
mail.main()
return 'qwe'
}
},
}
When the useSendMailQuery()
is being resolved it uses the resolver that calls the mail.main()
function and sends an email.当
useSendMailQuery()
被解析时,它使用解析器调用mail.main()
函数并发送电子邮件。 I want to use a function to send the email, not send the email when the component loads.我想使用一个功能来发送电子邮件,而不是在组件加载时发送电子邮件。
Any suggestions?有什么建议么?
Answer is using a lazy query: https://www.apollographql.com/docs/react/api/react/hooks/#uselazyquery答案是使用惰性查询: https ://www.apollographql.com/docs/react/api/react/hooks/#uselazyquery
const [sendMail, { called, loading: isMailing, data }] = useSendMailLazyQuery();
return (
<>
<div className="MyComponent">
data: {hello?.getHello}
</div>
<button onClick={() => sendMail()}>Send mail</button>
</>
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.