javascriptreactjsaxiosgoogle-analyticsgoogle-analytics-api

Can anyone help me recreate this exact same request but with GA4 format instead of the UA ID method am currently using?


This is the request am making using the UA method of calling the V3 API, wrapped in a oath library for react. But it's getting deprecated starting June 2023 and I can't figure out how to recreate it in the GA4 v1 Beta API aka Google Analytics Data API. I have tried following Google's documentation but i just can't for my life understand how to make the request...

const login = useGoogleLogin({
    onSuccess: async response => {
        try {
             console.log(response.access_token);
            const res = await axios.get(`https://www.googleapis.com/analytics/v3/data/realtime?ids=ga:${gaID}&metrics=rt:activeUsers&access_token=${response.access_token}`, {
                headers: {
                    "authorization": `Bearer ${response.access_token}`
                }
                
                
            })
            if (res.data.rows == null) {
                res.data.rows = 0
            }
            reponseGlobal = response
           
            setactiveUsers(res.data.rows);
            setloggedin(true);
            const interval = setInterval(function() {
                fetch ();
              }, 5000);
          
        } catch (err) {
            console.log(err)
        }
    },
    scope: 'https://www.googleapis.com/auth/analytics.readonly'
});



  

Solution

  • Currently there is no client library client library for react. You may have to code one yourself. The documentation describes all of the calls RunReportResponse

    There is a client library for node.js if you could switch to that Node.js quickstart

    Remember the API is still in Beta so they are still working on it.

    /**
       * TODO(developer): Uncomment this variable and replace with your
       *   Google Analytics 4 property ID before running the sample.
       */
      // propertyId = 'YOUR-GA4-PROPERTY-ID';
    
      // Imports the Google Analytics Data API client library.
      const {BetaAnalyticsDataClient} = require('@google-analytics/data');
    
      // Using a default constructor instructs the client to use the credentials
      // specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
      const analyticsDataClient = new BetaAnalyticsDataClient();
    
      // Runs a simple report.
      async function runReport() {
        const [response] = await analyticsDataClient.runReport({
          property: `properties/${propertyId}`,
          dateRanges: [
            {
              startDate: '2020-03-31',
              endDate: 'today',
            },
          ],
          dimensions: [
            {
              name: 'city',
            },
          ],
          metrics: [
            {
              name: 'activeUsers',
            },
          ],
        });
    
        console.log('Report result:');
        response.rows.forEach(row => {
          console.log(row.dimensionValues[0], row.metricValues[0]);
        });
      }
    
      runReport();
    

    As far as i can see there is no google cloud client library for JavaScript, this is where the data api normally lies. Without there being a client library for cloud i question weather or not they will create a library for JavaScript and reactjs

    Update

    I sent a message off to the team to ask if they were working on a react.js library for Analytics data api.

    The response was that there was no work planed at this time implement a data api library specifically designed for ReactJs

    They sugest the google-api-javascript-client Apparntly the GA4 Dimensions & Metrics Explorer uses it with ReactJs. They offer ga-dev-tools and onInitialClientRender.js as an example