我在使用Apollo客户端的React项目中使用打字稿,我有一个简单的update客户表单,该表单需要在Query内进行更改,才能从我创建的客户ID中获取客户数据(根据Apollo Typescript文档)为此的专用查询对象,
//---------------------------------------------------------------------------------
// Imports Section (React/Apollo Libs)
//---------------------------------------------------------------------------------
import { gql } from 'apollo-boost';
import { Query } from 'react-apollo'
import { getCustomerById } from '../../typeDefs/operations/getCustomerById'
import { getCustomerByIdVariables } from '../../typeDefs/operations/getCustomerById'
//---------------------------------------------------------------------------------
// GQL Query: Customers
//---------------------------------------------------------------------------------
export const Q_GET_CUSTOMER_BY_ID = gql`
query getCustomerById($id: ID) {
getCustomer(id: $id)
{
first_name
last_name
company
emails {
email
}
age
type
}
}
`;
//---------------------------------------------------------------------------------
// Query Class: Customers
//---------------------------------------------------------------------------------
export class QueryGetCustomerById extends Query<getCustomerById, getCustomerByIdVariables> { }
一切正常,直到更改后再次进入“ Edit Customer”视图,数据似乎保持不变(这显然是由于Apollo Cache),当尝试在{中使用“ refetchQuery”选项时{1}} Typescript向我的VSCode窗口发送了一个奇怪的错误。
阅读Apollo Typescript文档(非常缺少IMHO),我发现在第二个示例中有一个ChildProps对象的引用,现在我不确定是否应该为<QueryGetCustomerById>
声明或创建另一个接口来与Response和Variables一起使用。老实说,在这一点上,我完全感到困惑,如果有人尝试过或知道如何实施,请提供帮助。非常感谢。
P.S。使用更通用的版本QueryGetCustomerById
也不起作用。
答案 0 :(得分:0)
我的坏人...
在Apollo Docs网站上进行了更仔细的修订,我发现<Query>
标签可以将'refetch()'方法传递给返回箭头函数中的查询,而该方法又可以在突变后执行功能。我刚试过,效果很好!这是如果有人遇到相同问题并看到此页面的代码。
<QueryGetCustomerById
query={Q_GET_CUSTOMER_BY_ID}
variables={{ id: id }}
>
{({ loading, error, data, refetch }) => {
if (loading)
{
return "Put something that looks good for loading here..."
}
if (error)
{
return `Error: ${error.message}`
}
if (data && data.getCustomer)
{
this.setCustomer(id, data.getCustomer as CustomerInput)
}
return (
<div className="row justify-content-center">
<MutationUpdateCustomer
mutation={M_UPDATE_CUSTOMER}
onCompleted={() => this.props.history.push('/')}
>
{
(updateCustomer) => {
return (
<form name="frmEditCustomer"
className="col-md-8 m-3"
onSubmit={e => this.frmEditCustomer_submit(e, updateCustomer, refetch)}
onChange={e => this.frmEditCustomer_change(e)}
>
...
refetch()作为form_submit()事件处理程序中的另一个参数发送,因此以后可以执行...
try
{
await updateCustomer({
variables: { input }
})
await refetch()
Swal.fire(
'Update Customer',
'Customer data has been successfully saved.',
'success'
)
}
catch (error)
{
...
对于我来说,今天的教训是,如果不检查官方文档,不要相信我在网络上找到的任何博客文章。我希望这篇文章对某人可能有用。