Ads: don't fetch the impression URL more than once

This commit is contained in:
Alex Gleason 2022-10-20 12:39:22 -05:00
parent 400adfe0c6
commit ece6a00c2d
No known key found for this signature in database
GPG key ID: 7211D1F99744FBB7

View file

@ -1,4 +1,4 @@
import { useQueryClient } from '@tanstack/react-query'; import { useQuery, useQueryClient } from '@tanstack/react-query';
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import { FormattedMessage } from 'react-intl'; import { FormattedMessage } from 'react-intl';
@ -27,6 +27,14 @@ const Ad: React.FC<IAd> = ({ card, impression, expires }) => {
const infobox = useRef<HTMLDivElement>(null); const infobox = useRef<HTMLDivElement>(null);
const [showInfo, setShowInfo] = useState(false); const [showInfo, setShowInfo] = useState(false);
// Fetch the impression URL (if any) upon displaying the ad.
// Don't fetch it more than once.
useQuery(['ads', 'impression', impression], () => {
if (impression) {
return fetch(impression);
}
}, { cacheTime: Infinity, staleTime: Infinity });
/** Invalidate query cache for ads. */ /** Invalidate query cache for ads. */
const bustCache = (): void => { const bustCache = (): void => {
queryClient.invalidateQueries(['ads']); queryClient.invalidateQueries(['ads']);
@ -53,14 +61,6 @@ const Ad: React.FC<IAd> = ({ card, impression, expires }) => {
}; };
}, [infobox]); }, [infobox]);
// Fetch the impression URL (if any) upon displaying the ad.
// It's common for ad providers to provide this.
useEffect(() => {
if (impression) {
fetch(impression);
}
}, [impression]);
// Wait until the ad expires, then invalidate cache. // Wait until the ad expires, then invalidate cache.
useEffect(() => { useEffect(() => {
if (expires) { if (expires) {