【发布时间】:2021-04-03 05:12:38
【问题描述】:
这是我的 ApolloClient 的 React 代码
function EmpTable() {
const GET_EMPLOYEE = gql`
query refetch($id: String) {
employeeById(id: $id) {
id
name
role
}
}
`;
const {refetch} = useQuery(GET_EMPLOYEE)
const getEmpByID = (id) => {
refetch({
id: id
}).then((response) => {
// do something
})
}
return (
<div className="row">
{/* { I am rending list of employee with map and passing id this way
<a onClick={() => getEmpByID(id)}>get employ info</a>
} */}
</div>
);
}
export default EmpTable;
这段代码一切正常,唯一的问题是API被调用了两次,第一次没有返回数据,第二次返回了预期的数据。
如何防止调用两次?
我猜这是第一次执行:const {refetch} = useQuery(GET_EMPLOYEE) 并在没有数据的情况下发出第一个请求,因为那里没有传递任何变量。我知道我可以第一次在useQuery 中传递一个变量,但问题是我不能从那里传递这个变量,因为查询参数不在我的状态或道具中。
谁能告诉我可能的解决方案是什么?
【问题讨论】:
-
useLazyQuery? -
useLazyQuery 有 promise 方法吗?
-
如果触发我错误,则它不起作用
-
怎么用的?阅读文档
标签: reactjs graphql react-apollo apollo-client