export function useFxaFlowTracker()

in frontend/src/hooks/fxaFlowTracker.ts [21:79]


export function useFxaFlowTracker(
  args: FxaFlowTrackerArgs | null,
  options?: IntersectionOptions,
) {
  const runtimeData = useRuntimeData();
  const gaEvent = useGaEvent();
  const { ref } = useInView({
    threshold: 1,
    ...options,
    onChange: (inView, entry) => {
      if (args === null || !inView) {
        return;
      }
      gaEvent({
        ...args,
        action: "View",
        nonInteraction: true,
      });

      fetch(
        `${fxaOrigin}/metrics-flow?form_type=other&entrypoint=${encodeURIComponent(
          args.entrypoint,
        )}&utm_source=${encodeURIComponent(document.location.host)}`,
      )
        .then(async (response) => {
          if (!response.ok) {
            return;
          }
          const data = await response.json();
          if (
            typeof data.flowId !== "string" ||
            typeof data.flowBeginTime !== "number"
          ) {
            return;
          }
          setFlowData({
            flowBeginTime: data.flowBeginTime,
            flowId: data.flowId,
          });
        })
        .catch(() => {
          // Do nothing; if we can't contact the metrics endpoint,
          // we accept not being able to measure this.
        });

      if (typeof options?.onChange === "function") {
        options.onChange(inView, entry);
      }
    },
  });
  const [flowData, setFlowData] = useState<FlowData>();

  // If the API hasn't responded with the environment variables by the time this
  // hook fires, we assume we're dealing with the production instance of FxA:
  const fxaOrigin =
    runtimeData.data?.FXA_ORIGIN ?? "https://accounts.firefox.com";

  return { flowData: flowData, ref: ref };
}