I'm implementing a ReactJS app which is sending telemetry to App Insights. It's tracking PageViews ok except every PageView has the name "<App Name>" because that's our page title and it does not change between routes (for "reasons"). This makes our App Insights PageView data not as helpful as it could be.
I want to send the current route as the PageView name instead of the page title using a telemetry initializer. Problem is I get an error when I try to use the useLocation
hook to get the current route:
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
- You might have mismatching versions of React and the renderer (such as React DOM)
- You might be breaking the Rules of Hooks
- You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
Am using react-dom
v17 and react-router-dom
v6, so I'm probably "breaking the Rules". I might be using the App Insights SDK incorrectly as well.
Here is my <App />
where I'm currently using App Insights:
import { AppInsightsContext, ReactPlugin, withAITracking } from '@microsoft/applicationinsights-react-js';
import { ApplicationInsights, PageView } from '@microsoft/applicationinsights-web';
//<snip>
const reactPlugin = new ReactPlugin();
const appInsights = new ApplicationInsights({
config: {
connectionString: 'myconnectionstring',
extensions: [reactPlugin],
enableAutoRouteTracking: true,
enableCorsCorrelation: true,
enableRequestHeaderTracking: true,
enableResponseHeaderTracking: true,
},
);
appInsights.addTelemetryInitializer((envelope) => {
const telemetryItem = envelope.data.baseData;
if (envelope.name === PageView.envelopeType) {
const { pathname } = useLocation(); // runtime error
telemetryItem.name = pathname;
}
});
appInsights.loadAppInsights();
const App: React.FC = () => {
return (
<Provider store={store}>
<BrowserRouter>
<AppInsightsContext.Provider value={reactPlugin}>
<AppBootstrap />
<ToastContainer />
</AppInsightsContext.Provider>
</BrowserRouter>
</Provider>
);
};
export default withAITracking(reactPlugin, App);
Any ideas how I might be able to do this? Kinda new to React!