Utilizing React error boundary class with Google Analytics to track production errors in React apps.
Tags: react, googleanalytics, webdev, javascript
Published: 2023-01-19 08:09:46

The most frustrating aspect of web development is when a full program crashes in production as a result of undiagnosed faults and undetected problems during development. Examples include pressing a button and the entire screen going black or uncaught network request issues. A crucial aspect of the software development life cycle is creating web apps that are resilient to unanticipated faults. React is an open source Javascript UI library  used to create single-page applications.


**Error boundary**  is a React class component that prevents against run-time crashes of entire React applications or specific sections of them. They offer a personalized fallback error display screen along with a call to action, like a website reload icon or a go home button. 


Error boundaries provide a way for users to track and report errors within an application to a problem management tools such as **sentry**, **Atlassian Jira software** or **Google analytics**.

**React GA** is a simple React library that enables tracking and reporting of analytics for React apps via Google Analytics. This library offers a fine-tuned, customizable method of monitoring analysis and user events, such as user page visits, button clicks attached with an analytical tracker, and user experience reports.

Combining React GA library with React error boundary features offers a subtle way to communicate production application errors without having to wait for user feedback from the field. If you already have a react project, we can get started right away, or you can just use a tool like create-react-app or create-next-app to start from scratch.

### Getting started with React GA
We must first establish a property and obtain the tracking ID from the Google analytics interface before installing React GA and connecting our application to Google analytics. Here is a useful guide on how to register for one.[Integrating react app with Google analytics]( https://blog.saeloun.com/2022/02/17/how-to-integrate-react-app-with-google-analytics.html )
Next we install react GA to our react project
`npm install react-ga  --save`

 then we initiliaze it at the root of our app 
```javascript
import React from "react"
import ReactGA from "react-ga"
function App() {
  
React.useEffect(()=>{
// initialize react GA on root app, or _app.js if using next js,
const trackingId="UA-84757**"
ReactGA.initialize(trackingId)
},[])
// return your jsx mark up
return(...)
}
```

Also, we  track page views of our application with the following code just below ReactGA,initialize(trackingId).
`ReactGA.pageviews(window.location.pathname)`

### Creating an Error boundary
An error boundary is unique React class component that has a static class function called **getDerivedStateFromError** that receives an error, sets its state, and then returns it. Other features of a class components such as constructor and render method are necessary in addition to the static method.  

Whenever an error is detected, the error boundary class component receives a custom fallback functional component as a prop that will be rendered. The error object from the state is passed as a prop to the fallback functional component, where we write our Google analytics logic and show the user our unique error page.


As of React 18, there is no functional error boundary component, its a class component. 


```javascript
// ErrrorBoundary.js

import React, { Component } from "react";

export default class ErrorBoundary extends Component {
  state = { error: null };

  static getDerivedStateFromError (error) {
    // catches error,sets it to state then returns ot
    return { error };
  }

  render() {
    const { error } = this.state;
    const { children, fallback } = this.props;

    if (error) return <fallback error={error} />;
    return children;
  }
}

export  const ErrorFallbackComponent=({error})=>{
// we will write logic to handle and transmit error message to Google analytics here
  return (
    <div style={{padding:20,margin:20,background:"hotpink"}}>
<h3>Something went wrong</h3>
<p>{error?.message}</p>
</div>)
}
```
We then wrap our error boundary component to our app and pass the fallback component as  prop.

```javascript
import React from "react"
import ReactGA from "react-ga"
function App() {
  Import  ErrorBoundary, {ErrorFallbackComponent} from "./ErrrorBoundary"
React.useEffect(()=>{
// initialize react GA on root app, or _app.js if using //nextjs
const trackingId="UA-84757**" //From Googleanalytics console
ReactGA.initialize(trackingId)
},[])
// Basically your root app contains routes,layout or entry component of your app
return(
<ErrorBoundary fallback={ ErrorFallbackComponent}>
<ContentsOfYourApp/>
</ErrorBoundary>
)
}
```

In recap, we have enclosed our error component within our application.This class-based error component accepts a fallback component via props and has an error property of state object that is initially null declared in the constructor. The fallback component retrieves a custom UI using the error object as state. React GA must now be connected in order to report issues on the react error boundary.

### Connecting React GA to error boundary
React GA has an event method that can track actions from a specific section or event on your app,  the event takes an object with 3 properties category,action and label. For our case we are going to track and interpolate the following parameters to the **action** property.
1. Error message
2. Error page, where the error occurred
3. Date

We write the following function  logic inside  the  ErrorFallbackComponent.

```javascript
import React from "react";
import ReactGA from "react-ga";

export const ErrorFallbackComponent = ({ error }) => {
  const handleError = (errorMessage = "error boundary on react app") => {
    ReactGA.event({
      category: "Errors",
      action: errorMessage,
      label: "error boundary",
    });
  };
  //this effect will run every time the fallback component is rendered and transmit our error message to Google analytics
  React.useEffect(() => {
    const page = window.location.pathname;
    const date = new Date().toLocaleDateString();
    const message = error?.message;
    let errorMessage = `Error : ${message} on route: ${page} on date: ${date}`;
    // we call this handleError method
    handleError(errorMessage);
  }, []);

  return (
    <div style={{ padding: "1rem", background: "hotpink" }}>
      <h3>Something went wrong….Try again later</h3>
      <p>Message: {error?.message}</p>
      <button onClick={() => (window.location.pathname = "/")}>
        Take me home
      </button>
    </div>
  );
};
```

To test this, we create a function that, when a button is clicked, throws an error and displays it in our application. To see the differences, display the same function without an error boundary wrapping.

```javascript
const ThrowErrorComponent=()=>{

const breakThings=()=>{
throw new Error("Move fast and break things")
}
  
return (
<div>
<button onClick={breakThings}>Break things </button>
</div>)
}
```

### Reading error messages  on Google analytics console
To read error  messages , visit your Google analytics console on **Behavior** > **Events** > **overview**  and you will see your event action reported as such:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kzsfmjaj47o96evvnldt.png)

Lastly, if you want to only track your errors in production environment, add the following line of code to useEffect hook of ErrorFallbackComponent.
```javascript
React.useEffect(()=>{
const page=window.location.pathname
const date=new Date().toLocaleDateString()
const  message=error?.message
let errorMessage=`Error : ${message} on route: ${page} on date: ${date}`;
// we call this handleError method
// we check to see if the app is production, if so, call the error handle function
if(process.env.NODE_ENV !== "development") handleError(errorMessage)
},[])
```


That's all; your application will now gracefully manage problems and immediately notify Google Analytics of critical production errors.