My team uses the query function returned by useLazyQuery
along with useEffect
to control when queries are executed. In some situations we wish to include information in the query’s context object that is consumed by a custom ApolloLink
middleware function. (We are still using Apollo v3.2.7.)
When we use a pattern like the one shown below, where the context object is a part of the options passed to useLazyQuery
, we observe that our custom ApolloLink
middleware receives the expected context object when processing the first query executed on mount.
// the contents of the customContext object change over time...
const customContext = getCustomContext();
const [getProductDetails] = useLazyQuery(PRODUCT_DETAILS_SEARCH, {
context: customContext,
});
// trigger query on mount and each time `productId` prop changes.
useEffect(() => {
getProductDetails({ variables: { id: productId } });
},
[getProducts, productId]);
However, if we include the context in the options passed to the executor function, as seen in the example below, we observe that the contents of customContext
do not reach our ApolloLink
middleware on the first execution of the query. But the customContext
object intended to be sent in the first query is present on the next execution of the query (here triggered by a change in the productId prop.)
const customContext = generateCustomContextViaHook();
const [getProductDetails] = useLazyQuery(PRODUCT_DETAILS_SEARCH, {
onCompleted: () => clearCustomContext();
});
useEffect(() => {
getProductDetails({ variables: { id: productId }, context: customContext });
},
[getProducts, productId]);
There seems to be a difference in how the context included in the query’s options object is processed when provided directly to the useLazyQuery
hook, or via the executor function the hook returns. Is this behavior to be expected?