Skip to content

Commit

Permalink
[useCurrentUser] avoid pushing to dataLayer too often
Browse files Browse the repository at this point in the history
MrOrz authored and johnson-liang committed May 20, 2020
1 parent 2c884cb commit c36969b
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions lib/useCurrentUser.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useEffect } from 'react';
import { useLazyQuery } from '@apollo/react-hooks';
import gql from 'graphql-tag';
import { usePushToDataLayer } from './gtm';
import { pushToDataLayer } from './gtm';

export const CurrentUser = gql`
fragment CurrentUser on User {
@@ -22,10 +22,21 @@ const USER_QUERY = gql`
/**
* Loads currentUser on browser load. Should load from cache first.
*/
let pushDataLayerHandle;
function useCurrentUser() {
const [loadUser, { data }] = useLazyQuery(USER_QUERY);
const [loadUser, { data }] = useLazyQuery(USER_QUERY, {
onCompleted(data) {
// If multiple component with useCurrentUser() is mounted in the same time,
// onCompleted will be invoked multiple times.
//
// We use setTimeout to get rid of duplicated onCompleted calls.
clearTimeout(pushDataLayerHandle);
pushDataLayerHandle = setTimeout(() => {
pushToDataLayer({ CURRENT_USER: data?.GetUser });
}, 10);
},
});
useEffect(() => loadUser(), []);
usePushToDataLayer(data?.GetUser, { CURRENT_USER: data?.GetUser });

return data?.GetUser;
}

0 comments on commit c36969b

Please sign in to comment.