gpt4 book ai didi

reactjs - React apollo 客户端 api 调用两次

转载 作者:行者123 更新时间:2023-12-05 04:55:20 26 4
gpt4 key购买 nike

这是我的 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 中传递一个变量,但问题是我不能从那里传递这个变量,因为查询参数不在我的状态或 Prop 中。

谁能告诉我可能的解决方案是什么?

最佳答案

由于文档:

When React mounts and renders a component that calls the useQueryhook, Apollo Client automatically executes the specified query. Butwhat if you want to execute a query in response to a different event,such as a user clicking a button? The useLazyQuery hook is perfect forexecuting queries in response to events other than componentrendering. This hook acts just like useQuery, with one key exception:when useLazyQuery is called, it does not immediately execute itsassociated query. Instead, it returns a function in its result tuplethat you can call whenever you're ready to execute the query:

示例:

const GET_COUNTRIES = gql`
{
countries {
code
name
}
}
`;
export function DelayedCountries() {
const [getCountries, { loading, data }] = useLazyQuery(GET_COUNTRIES);
if (loading) return <p>Loading ...</p>;

if (data && data.countries) {
console.log(data.countries);
}

return (
<div>
<button onClick={() => getCountries()}>
Click me to print all countries!
</button>
{data &&
data.countries &&
data.countries.map((c, i) => <div key={i}>{c.name}</div>)}
</div>
);
}

useLazyQuery 将在调用 getCountries 时执行。

https://codesandbox.io/s/apollo-client-uselazyquery-example-6ui35?file=/src/Countries.js

关于reactjs - React apollo 客户端 api 调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65443598/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com