First draft of GroupRelationship entity hooks
This commit is contained in:
parent
8923e7b5d0
commit
9964491da5
1 changed files with 31 additions and 3 deletions
|
@ -1,13 +1,14 @@
|
|||
import { useEffect } from 'react';
|
||||
|
||||
import { useEntities, useEntity } from 'soapbox/entity-store/hooks';
|
||||
import { normalizeGroup } from 'soapbox/normalizers';
|
||||
import { normalizeGroup, normalizeGroupRelationship } from 'soapbox/normalizers';
|
||||
|
||||
import type { Group } from 'soapbox/types/entities';
|
||||
import type { Group, GroupRelationship } from 'soapbox/types/entities';
|
||||
|
||||
function useGroups() {
|
||||
const result = useEntities<Group>(['Group', ''], '/api/v1/groups');
|
||||
const { entities, isLoading, fetchEntities } = result;
|
||||
const { entities: relationships } = useGroupRelationships(entities.map(entity => entity.id));
|
||||
|
||||
// Note: we have to fetch them in the hook right now because I haven't implemented
|
||||
// max-age or cache expiry in the entity store yet. It's planned.
|
||||
|
@ -17,9 +18,19 @@ function useGroups() {
|
|||
}
|
||||
}, []);
|
||||
|
||||
const groups = entities.map((entity) => {
|
||||
const group = normalizeGroup(entity);
|
||||
// TODO: a generalistic useRelationships() hook that returns a map of values (would be faster).
|
||||
const relationship = relationships.find(r => r.id === group.id);
|
||||
if (relationship) {
|
||||
return group.set('relationship', relationship);
|
||||
}
|
||||
return group;
|
||||
});
|
||||
|
||||
return {
|
||||
...result,
|
||||
groups: entities.map(normalizeGroup),
|
||||
groups,
|
||||
};
|
||||
}
|
||||
|
||||
|
@ -39,4 +50,21 @@ function useGroup(groupId: string) {
|
|||
};
|
||||
}
|
||||
|
||||
function useGroupRelationships(groupIds: string[]) {
|
||||
const q = groupIds.map(id => `id[]=${id}`).join('&');
|
||||
const result = useEntities<GroupRelationship>(['GroupRelationship', ''], `/api/v1/groups/relationships?${q}`);
|
||||
const { entities, isLoading, fetchEntities } = result;
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoading) {
|
||||
fetchEntities();
|
||||
}
|
||||
}, groupIds);
|
||||
|
||||
return {
|
||||
...result,
|
||||
relationships: entities.map(normalizeGroupRelationship),
|
||||
};
|
||||
}
|
||||
|
||||
export { useGroup, useGroups };
|
Loading…
Reference in a new issue