'Google tag manager not working on initial load

I am implementing Google tag manager for my Laravel-React app and using react as SPA. I return index.blade.php file for all routes.

It is working fine for non logged in users but for logged in users, user_id is not getting set on first page load. When I navigate to other routes, the user_id is set.

I am using API authentication using Laravel passport therefore I am updating the user_id used in index.blade.php from react component.

Here is my code

index.blade.php

<!-- Google Tag Manager -->
    <script>

        (function (w, d, s, l, i) {

            w[l] = w[l] || [];
            w[l].push({
                'gtm.start':
                    new Date().getTime(), event: 'gtm.js'
            });
            var f = d.getElementsByTagName(s)[0],
                j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : '';
            j.async = true;
            j.src =
                'https://www.googletagmanager.com/gtm.js?id=' + i + dl;
            f.parentNode.insertBefore(j, f);
        })(window, document, 'script', 'dataLayer', '{{$google_tag_manager_id}}');

        (function() {
            window.authUserId = '';
            window.dataLayer = window.dataLayer || [];
            let interval = setInterval(function () {
                console.log('dataLayer-outside', window.dataLayer);
                if (window.authUserId) {
                    console.log('dataLayer-inside', window.dataLayer);
                    console.log('Auth id-IN5: ', window.authUserId);
                    window.dataLayer = window.dataLayer || [];
                    window.dataLayer.push({
                        'event' : 'login',
                        'visitorId' : window.authUserId
                    });
                    clearInterval(interval);
                }
            }, 5000)
        })();
    </script>
    <!-- End Google Tag Manager -->

<body>
<!-- Google Tag Manager (noscript) -->
<noscript>
    <iframe src="https://www.googletagmanager.com/ns.html?id={{$google_tag_manager_id}}"
                  height="0" width="0" style="display:none;visibility:hidden"></iframe>
</noscript>
<!-- End Google Tag Manager (noscript) -->

Main.jsx

const authUser = useSelector(state => state.auth.auth_user);

useEffect(() => {
    window.authUserId = authUser?.id;
}, [authUser]);


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source