lbry-desktop/ui/effects/use-get-user-memberships.js

69 lines
2.5 KiB
JavaScript
Raw Normal View History

// @flow
2022-03-17 18:53:46 +01:00
import { useEffect } from 'react';
import { getChannelFromClaim } from 'util/claim';
export default function useGetUserMemberships(
shouldFetchUserMemberships: ?boolean,
arrayOfContentUris: ?Array<string>,
2022-03-16 21:03:08 +01:00
convertClaimUrlsToIds: any, //
doFetchUserMemberships: (string) => void, // fetch membership values and save in redux
dependency?: any,
2022-03-17 18:53:46 +01:00
alreadyClaimIds?: boolean
) {
2022-03-17 18:53:46 +01:00
// instantiate variable if it doesn't exist yet
if (!window.checkedMemberships) window.checkedMemberships = {};
useEffect(() => {
2022-03-16 21:03:08 +01:00
// run if there's uris to check
if (shouldFetchUserMemberships && arrayOfContentUris && arrayOfContentUris.length > 0) {
const urisToFetch = arrayOfContentUris;
let claimIds;
2022-03-16 21:03:08 +01:00
// convert content urls to channel claim ids
if (!alreadyClaimIds) {
claimIds = urisToFetch.map((uri) => {
2022-03-17 18:53:46 +01:00
// get claim id
const contentClaimId = convertClaimUrlsToIds[uri];
// return channel claim id
if (contentClaimId) return getChannelFromClaim(contentClaimId)?.claim_id;
});
} else {
2022-03-16 21:03:08 +01:00
// call already comes with an array of channel claim ids
claimIds = arrayOfContentUris;
}
2022-03-17 18:53:46 +01:00
// remove dupes and falsey values
const dedupedChannelIds = [...new Set(claimIds)].filter(Boolean);
2022-03-16 21:03:08 +01:00
// check if channel id has already been fetched
const channelsToFetch = dedupedChannelIds.filter(
2022-03-17 18:53:46 +01:00
// if value exists or is null it's been through the backend
(channelClaimId) =>
!window.checkedMemberships[channelClaimId] && window.checkedMemberships[channelClaimId] !== null
);
2022-03-17 18:53:46 +01:00
// create csv string for backend
const commaSeparatedStringOfIds = channelsToFetch.join(',');
2022-03-16 21:03:08 +01:00
// new channels to hit, hit check api and save in state
if (channelsToFetch && channelsToFetch.length > 0) {
2022-03-17 18:53:46 +01:00
// setup object to be added to window
2022-03-16 21:03:08 +01:00
let membershipsToAdd = {};
for (const channelToFetch of channelsToFetch) {
2022-03-17 18:53:46 +01:00
// mark as waiting while waiting for backend, so won't recall
2022-03-16 21:03:08 +01:00
membershipsToAdd[channelToFetch] = 'waiting';
}
2022-03-17 18:53:46 +01:00
// update checked memberships
window.checkedMemberships = Object.assign(window.checkedMemberships, membershipsToAdd);
2022-03-16 21:03:08 +01:00
// hit membership/check and save it in redux
if (doFetchUserMemberships) {
doFetchUserMemberships(commaSeparatedStringOfIds);
}
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, dependency || [arrayOfContentUris]);
}