reactjs – Graphql Apollo chaining lazy queries in onCompleted gives weird behaviour
I have a component with these functions and hooks. In the useffect everything happens as expected, but when I use the getMenuItem() seperately in another function the onCompleted callback from useMenuTreeLazyQuery gets invoked even though the useEffect does not run (is the only place menuTree() is used). What is happening here? does both onCompleted from both hooks gets invoked when one of them is activated?
possible issue (just thinking):
- they both return a list of MenuItems, so when the apollo cache gets populated with the first query the second querys onCompleted gets invoked because it detected changes?
my code:
const populateMenu = (data?: MenuTree | MenuItemList | null) => {
const getVisibleMenu = data?.filter((menu) => menu?.visible) || [];
setMenuContent(getVisibleMenu);
};
const [getMenuItem, { error: menuItemError }] = useGetMenuItemLazyQuery({
onCompleted: (data) => {
console.log('ITEM complete');
if (menuItemError) {
setError(generalMenuErrorText);
return null;
}
populateMenu(data.menuItem);
},
});
const [menuTree, { error: menuTreeError }] = useMenuTreeLazyQuery({
onCompleted: (data) => {
console.log('TREE complete');
if (menuTreeError) {
setError(generalMenuErrorText);
return null;
}
if (menuIdInit) {
getMenuItem({
variables: {
query: Number(menuIdInit),
},
});
} else {
populateMenu(data.menuTree);
}
},
});
useEffect(() => {
if (open) {
menuTree({
variables: {
relativeUrl,
},
});
}
}, [menuTree, open, relativeUrl]);
Read more here: Source link