1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-02-23 00:22:19 +01:00

Fix/use swr bug (#2884)

This PR fixes an error where useSWR would throw a TypeError: `subs[i] is
not a function`: https://github.com/vercel/swr/issues/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.
This commit is contained in:
Fredrik Strand Oseberg 2023-01-12 11:25:42 +01:00 committed by GitHub
parent aa19ad57eb
commit ea31154d9a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 82 additions and 35 deletions

View File

@ -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';
@ -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>>;
@ -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>

View File

@ -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 (
<>
@ -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>
@ -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!}
/>
</>
);
};

View File

@ -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>>;
@ -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(
@ -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}
@ -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>
@ -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>
);
};

View File

@ -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}

View File

@ -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[];
@ -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,
}
@ -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())