bigbuffet-rw/app/soapbox/queries/ads.ts

40 lines
889 B
TypeScript
Raw Normal View History

2022-08-01 20:43:28 -07:00
import { useQuery } from '@tanstack/react-query';
import { Ad, getProvider } from 'soapbox/features/ads/providers';
import { useAppDispatch } from 'soapbox/hooks';
2022-10-20 14:29:14 -07:00
import { normalizeAd } from 'soapbox/normalizers';
import { isExpired } from 'soapbox/utils/ads';
2022-08-01 20:43:28 -07:00
const AdKeys = {
2022-09-27 12:42:24 -07:00
ads: ['ads'] as const,
};
function useAds() {
2022-08-01 20:43:28 -07:00
const dispatch = useAppDispatch();
const getAds = async () => {
return dispatch(async (_, getState) => {
2022-08-01 20:43:28 -07:00
const provider = await getProvider(getState);
if (provider) {
return provider.getAds(getState);
} else {
return [];
}
});
};
const result = useQuery<Ad[]>(AdKeys.ads, getAds, {
2022-08-01 20:43:28 -07:00
placeholderData: [],
});
2022-08-26 07:48:49 -07:00
// Filter out expired ads.
2022-10-20 14:29:14 -07:00
const data = result.data?.map(normalizeAd).filter(ad => !isExpired(ad));
2022-08-26 07:48:49 -07:00
return {
...result,
data,
};
2022-08-01 20:43:28 -07:00
}
2022-09-27 12:42:24 -07:00
export { useAds as default, AdKeys };