Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix skipFirstRun at useCustomEvent in strict mode #55

Merged
merged 1 commit into from
Sep 26, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions applicationinsights-react-js/src/useTrackEvent.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* ReactPlugin.ts
* @copyright Microsoft 2019
*/
* ReactPlugin.ts
* @copyright Microsoft 2019
*/
import ReactPlugin from "./ReactPlugin";
import { Dispatch, SetStateAction, useEffect, useRef, useState } from "react";

Expand All @@ -15,6 +15,7 @@ export default function useCustomEvent<T>(
): AIReactCustomEvent<T> {
const [data, setData] = useState(eventData);
const firstRun = useRef(skipFirstRun);
const savedSkipFirstRun = useRef(skipFirstRun);

useEffect(() => {
if (firstRun.current) {
Expand All @@ -24,5 +25,11 @@ export default function useCustomEvent<T>(
reactPlugin.trackEvent({ name: eventName }, data);
}, [reactPlugin, data, eventName]);

useEffect(() => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Based on the issue, would this not be better as a specific listener for when the component is being "unmounted" as won't this always cause the "firstRun" to get reset directly after it's mounted thereby bypassing the if check on line 21 with a side effect of causing multiple trackEvent calls when the useEffect is called again (I don't know react well enough to understand if this is even (generally) possible))

Copy link
Contributor Author

@szilagyi-sandor szilagyi-sandor Sep 8, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is exactly the "unmounted" listener you are describing. That's the reason why it's in a different useEffect hook. If you take a closer look it's not calling the reset inside directly, but it's returning a function that does the work. This function is the "cleanup" function, which will only be called when the component unmounts, since it does not have any dependencies. You can read more about it here if you want: https://react.dev/reference/react/useEffect .

return () => {
firstRun.current = savedSkipFirstRun.current;
};
}, []);

return setData as AIReactCustomEvent<T>;
}