我正在尝试新的Apollo React Hooks,并建立了一个小型商业示例。
^[
一切正常,删除/添加项目会正确刷新项目列表,但是在执行任何突变后,查询的function App() {
const [cartId, setCartId] = useState('V1bvif5UxQThb84iukrxHx9dYQg9nr8j');
const [removeItem, {loading: mutationLoading}] = useMutation(REMOVE_ITEM, {
refetchQueries: [{query: CART_DETAILS, variables: {cartId}}]
});
const [addToCart] = useMutation(ADD_TO_CART, {
refetchQueries: [{query: CART_DETAILS, variables: {cartId}}]
});
const {data, loading, error} = useQuery(CART_DETAILS, {
variables: {cartId}
});
if (data && data.items) {
console.log(`We have data`, data);
}
const handleRemove = itemId => {
console.log(`Removing item with id ${itemId}`);
removeItem({
variables: {cartId, itemId}
});
};
if (error) {
console.log(`Some error happened`, error);
return <h2>ERROR!</h2>;
}
if (loading) {
return <p>Loading...</p>;
}
return ( ... some HTML skipped for brevity )
状态永远不会为真(结果是我看不到{ UI中的{1}}消息。
loading
和Loading...
变量不是应该在重新获取查询时更新吗?
答案 0 :(得分:1)
refetchQueries
不会导致监视的查询的loading
属性发生变化-它只是异步解析列出的查询并使用结果更新缓存。
useMutation
还公开了loading
属性。我相信您可以通过将awaitRefetchQueries
设置为true来达到所需的效果。
const [removeItem, {loading: removeLoading}] = useMutation(REMOVE_ITEM, {
refetchQueries: [{query: CART_DETAILS, variables: {cartId}}],
awaitRefetchQueries: true,
});
const [addToCart, {loading: addLoading}] = useMutation(ADD_TO_CART, {
refetchQueries: [{query: CART_DETAILS, variables: {cartId}}],
awaitRefetchQueries: true,
});
const loading = queryLoading || addLoading || removeLoading
另一种方法是直接直接调用查询的refetch方法。