Skip to content

Commit

Permalink
Fix/use swr bug (#2884)
Browse files Browse the repository at this point in the history
This PR fixes an error where useSWR would throw a TypeError: `subs[i] is
not a function`: vercel/swr#2357

I can't be totally sure why this is happening but we had a design flaw
in our setup that caused our group overview to first fetch all groups,
and then subsequently fetch each individual group after the groups were
rendered. This was happening because GroupCard was rendering the
EditGroupUsers component which used the `useGroup(groupId)` getter.

The flow in the old version looked like this: 

1. Fetch all the groups
2. Use the groups data to render all the `GroupCard` elements
3. Once the GroupCard was rendered the EditGroupComponent would be
mounted and set up a recurring GET on the individual group, causing each
group to be fetched recurringly in the Group overview.

The useSWR error seems to be connected to setting up these
subscriptions, and then removing the element from the DOM. We were able
to trigger this error by removing the group.

## How did we fix it? 

We refactored the components concerned with editing group users and
removing groups to exist outside of the `GroupCard` and have the group
card supply the base data through a state setter. This pattern is also
better for the remove functionality because the remove functionality in
its current state could trigger a react update on a component removed
from the DOM if you awaited the refetching of the data. This is because
the groups data is controlling the rendering of the `GroupCard` and when
the `RemoveGroup` modal is nested underneath the `GroupCard` a refetch
would trigger an update, re-render the overview and remove the entire
`GroupCard` and the associated `RemoveGroup` component.

I'm still not sure if this is a bug with SWR or a side-effect of how we
architected the functionality, but this change seems to remove the
problem.
  • Loading branch information
FredrikOseberg committed Jan 12, 2023
1 parent aa19ad5 commit ea31154
Show file tree
Hide file tree
Showing 5 changed files with 82 additions and 35 deletions.
@@ -1,4 +1,4 @@
import { Button, styled } from '@mui/material';
import { Button, styled, Box } from '@mui/material';
import FormTemplate from 'component/common/FormTemplate/FormTemplate';
import { SidebarModal } from 'component/common/SidebarModal/SidebarModal';
import { useGroupApi } from 'hooks/api/actions/useGroupApi/useGroupApi';
Expand Down Expand Up @@ -35,6 +35,10 @@ const StyledCancelButton = styled(Button)(({ theme }) => ({
marginLeft: theme.spacing(3),
}));

const StyledBox = styled(Box)(({ theme }) => ({
marginTop: theme.spacing(2),
}));

interface IEditGroupUsersProps {
open: boolean;
setOpen: React.Dispatch<React.SetStateAction<boolean>>;
Expand Down Expand Up @@ -122,21 +126,23 @@ export const EditGroupUsers: FC<IEditGroupUsersProps> = ({
</div>

<StyledButtonContainer>
<Button
type="submit"
variant="contained"
color="primary"
data-testid={UG_SAVE_BTN_ID}
>
Save
</Button>
<StyledCancelButton
onClick={() => {
setOpen(false);
}}
>
Cancel
</StyledCancelButton>
<StyledBox>
<Button
type="submit"
variant="contained"
color="primary"
data-testid={UG_SAVE_BTN_ID}
>
Save
</Button>
<StyledCancelButton
onClick={() => {
setOpen(false);
}}
>
Cancel
</StyledCancelButton>
</StyledBox>
</StyledButtonContainer>
</StyledForm>
</FormTemplate>
Expand Down
Expand Up @@ -80,11 +80,15 @@ const ProjectBadgeContainer = styled('div')(({ theme }) => ({

interface IGroupCardProps {
group: IGroup;
onEditUsers: (group: IGroup) => void;
onRemoveGroup: (group: IGroup) => void;
}

export const GroupCard = ({ group }: IGroupCardProps) => {
const [editUsersOpen, setEditUsersOpen] = useState(false);
const [removeOpen, setRemoveOpen] = useState(false);
export const GroupCard = ({
group,
onEditUsers,
onRemoveGroup,
}: IGroupCardProps) => {
const navigate = useNavigate();
return (
<>
Expand All @@ -95,8 +99,8 @@ export const GroupCard = ({ group }: IGroupCardProps) => {
<StyledHeaderActions>
<GroupCardActions
groupId={group.id}
onEditUsers={() => setEditUsersOpen(true)}
onRemove={() => setRemoveOpen(true)}
onEditUsers={() => onEditUsers(group)}
onRemove={() => onRemoveGroup(group)}
/>
</StyledHeaderActions>
</StyledTitleRow>
Expand Down Expand Up @@ -150,16 +154,6 @@ export const GroupCard = ({ group }: IGroupCardProps) => {
</StyledBottomRow>
</StyledGroupCard>
</StyledLink>
<EditGroupUsers
open={editUsersOpen}
setOpen={setEditUsersOpen}
group={group}
/>
<RemoveGroup
open={removeOpen}
setOpen={setRemoveOpen}
group={group!}
/>
</>
);
};
45 changes: 44 additions & 1 deletion frontend/src/component/admin/groups/GroupsList/GroupsList.tsx
Expand Up @@ -16,6 +16,8 @@ import ResponsiveButton from 'component/common/ResponsiveButton/ResponsiveButton
import { ADMIN } from 'component/providers/AccessProvider/permissions';
import { Add } from '@mui/icons-material';
import { NAVIGATE_TO_CREATE_GROUP } from 'utils/testIds';
import { EditGroupUsers } from '../Group/EditGroupUsers/EditGroupUsers';
import { RemoveGroup } from '../RemoveGroup/RemoveGroup';

type PageQueryType = Partial<Record<'search', string>>;

Expand All @@ -37,6 +39,11 @@ const groupsSearch = (group: IGroup, searchValue: string) => {

export const GroupsList: VFC = () => {
const navigate = useNavigate();
const [editUsersOpen, setEditUsersOpen] = useState(false);
const [removeOpen, setRemoveOpen] = useState(false);
const [activeGroup, setActiveGroup] = useState<IGroup | undefined>(
undefined
);
const { groups = [], loading } = useGroups();
const [searchParams, setSearchParams] = useSearchParams();
const [searchValue, setSearchValue] = useState(
Expand Down Expand Up @@ -65,6 +72,16 @@ export const GroupsList: VFC = () => {
: sortedGroups;
}, [groups, searchValue]);

const onEditUsers = (group: IGroup) => {
setActiveGroup(group);
setEditUsersOpen(true);
};

const onRemoveGroup = (group: IGroup) => {
setActiveGroup(group);
setRemoveOpen(true);
};

return (
<PageContent
isLoading={loading}
Expand Down Expand Up @@ -115,7 +132,11 @@ export const GroupsList: VFC = () => {
<Grid container spacing={2}>
{data.map(group => (
<Grid key={group.id} item xs={12} md={6}>
<GroupCard group={group} />
<GroupCard
group={group}
onEditUsers={onEditUsers}
onRemoveGroup={onRemoveGroup}
/>
</Grid>
))}
</Grid>
Expand All @@ -136,6 +157,28 @@ export const GroupsList: VFC = () => {
/>
}
/>

<ConditionallyRender
condition={Boolean(activeGroup)}
show={
<EditGroupUsers
open={editUsersOpen}
setOpen={setEditUsersOpen}
group={activeGroup!}
/>
}
/>

<ConditionallyRender
condition={Boolean(activeGroup)}
show={
<RemoveGroup
open={removeOpen}
setOpen={setRemoveOpen}
group={activeGroup!}
/>
}
/>
</PageContent>
);
};
Expand Up @@ -51,6 +51,7 @@ export const BaseModal: FC<ISidebarModalProps> = ({
BackdropComponent={Backdrop}
BackdropProps={{ timeout: TRANSITION_DURATION }}
data-testid={SIDEBAR_MODAL_ID}
sx={{ minHeight: '100vh' }}
>
<Fade timeout={TRANSITION_DURATION} in={open}>
{children}
Expand Down
9 changes: 6 additions & 3 deletions frontend/src/hooks/api/getters/useSegments/useSegments.ts
Expand Up @@ -4,6 +4,7 @@ import { formatApiPath } from 'utils/formatPath';
import handleErrorResponses from '../httpErrorResponseHandler';
import { ISegment } from 'interfaces/segment';
import useUiConfig from 'hooks/api/getters/useUiConfig/useUiConfig';
import { useConditionalSWR } from '../useConditionalSWR/useConditionalSWR';

export interface IUseSegmentsOutput {
segments?: ISegment[];
Expand All @@ -19,9 +20,11 @@ export const useSegments = (strategyId?: string): IUseSegmentsOutput => {
? formatApiPath(`api/admin/segments/strategies/${strategyId}`)
: formatApiPath('api/admin/segments');

const { data, error, mutate } = useSWR(
const { data, error, mutate } = useConditionalSWR(
Boolean(uiConfig.flags?.SE),
[],
url,
() => (uiConfig.flags?.SE ? fetchSegments(url) : []),
() => fetchSegments(url),
{
refreshInterval: 15 * 1000,
}
Expand All @@ -39,7 +42,7 @@ export const useSegments = (strategyId?: string): IUseSegmentsOutput => {
};
};

export const fetchSegments = async (url: string): Promise<ISegment[]> => {
export const fetchSegments = async (url: string) => {
return fetch(url)
.then(handleErrorResponses('Segments'))
.then(res => res.json())
Expand Down

0 comments on commit ea31154

Please sign in to comment.