Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor/query hooks #205

Merged
merged 4 commits into from
Jan 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 19 additions & 14 deletions src/components/AreaCoordinates/AreaCoordinates.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import {
UpdateAnalogueModelAreaCommandForm,
} from '../../api/generated';
import { AnalogueModelsService } from '../../api/generated/services/AnalogueModelsService';
import { queryClient } from '../../auth/queryClient';
import { useFetchModel } from '../../hooks/useFetchModel';
import * as Styled from './AreaCoordinates.styled';
import { CoordinateInput } from './CoordinateInput/CoordinateInput';

Expand Down Expand Up @@ -61,7 +63,6 @@ export const AreaCoordinates = ({ modelId }: { modelId: string }) => {
const [showSaveAlert, setSaveAlert] = useState(false);
const [activeArea, setActiveArea] = useState<ModelAreaTypeDto>(defaultArea);
const [newArea, setNewArea] = useState<ModelAreaTypeDto>();
const [updated, setUpdated] = useState(1);
const [errors, setErrors] = useState<ErrorType>({});
const [submitting, setSubmitting] = useState(false);
const [areaCoordinate, setAreaCoordinate] = useState<AreaCoordinateType>({
Expand All @@ -88,10 +89,7 @@ export const AreaCoordinates = ({ modelId }: { modelId: string }) => {
return isNaN(value);
}

const model = useQuery({
queryKey: ['analogue-model', modelId, updated],
queryFn: () => AnalogueModelsService.getApiAnalogueModels1(modelId),
});
const { data, isLoading } = useFetchModel(modelId);

const modelAreas = useQuery({
queryKey: ['model-area'],
Expand All @@ -111,6 +109,9 @@ export const AreaCoordinates = ({ modelId }: { modelId: string }) => {
requestBody,
);
},
onSuccess: () => {
queryClient.refetchQueries({ queryKey: ['analogue-model'] });
},
});

const putAreaCoordinates = useMutation({
Expand All @@ -129,6 +130,9 @@ export const AreaCoordinates = ({ modelId }: { modelId: string }) => {
requestBody,
);
},
onSuccess: () => {
queryClient.refetchQueries({ queryKey: ['analogue-model'] });
},
});

const handleSelectChange = async (
Expand Down Expand Up @@ -160,8 +164,7 @@ export const AreaCoordinates = ({ modelId }: { modelId: string }) => {
return;
}

const selectableAreas =
model.data?.data?.modelAreas && model.data?.data?.modelAreas;
const selectableAreas = data?.data?.modelAreas && data?.data?.modelAreas;

const selectedArea = selectableAreas?.filter(
(area) => area.modelAreaType === changes.selectedItems[0].name,
Expand Down Expand Up @@ -298,7 +301,7 @@ export const AreaCoordinates = ({ modelId }: { modelId: string }) => {
return errors;
};

const clearAndUpdate = () => {
const clearAndUpdate = async () => {
setActiveArea(defaultArea);
setAreaCoordinate({
modelAreaId: '',
Expand All @@ -315,8 +318,7 @@ export const AreaCoordinates = ({ modelId }: { modelId: string }) => {
},
],
});
setUpdated(updated + 1);
setSaveAlert(true);
return 'success';
};

const postModelArea = async () => {
Expand All @@ -332,7 +334,8 @@ export const AreaCoordinates = ({ modelId }: { modelId: string }) => {
});

if (coordinateRes.success) {
clearAndUpdate();
const res = await clearAndUpdate();
if (res === 'success') setSaveAlert(true);
}
}
};
Expand All @@ -344,7 +347,8 @@ export const AreaCoordinates = ({ modelId }: { modelId: string }) => {
requestBody: { coordinates: areaCoordinate.coordinates },
});
if (coordinateRes.success) {
clearAndUpdate();
const res = await clearAndUpdate();
if (res === 'success') setSaveAlert(true);
}
};

Expand Down Expand Up @@ -383,7 +387,7 @@ export const AreaCoordinates = ({ modelId }: { modelId: string }) => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [errors, submitting]);

if (modelAreas.isLoading || modelAreas.data === undefined || model.isLoading)
if (modelAreas.isLoading || modelAreas.data === undefined || isLoading)
return <p>Loading.....</p>;

return (
Expand All @@ -393,7 +397,7 @@ export const AreaCoordinates = ({ modelId }: { modelId: string }) => {
<Styled.Form>
<Styled.Info>
<Typography variant="h6">
{model.data?.success && model.data.data.name}
{data?.success && data.data.name}
</Typography>
<Typography variant="body_long">
Select from predefined model areas and set the X/Y coordinates for
Expand All @@ -407,6 +411,7 @@ export const AreaCoordinates = ({ modelId }: { modelId: string }) => {
options={modelAreas.data.data}
optionLabel={(option) => option.name}
onOptionsChange={handleSelectChange}
selectedOptions={[activeArea]}
variant={errors.area ? 'error' : undefined}
></Autocomplete>
</Styled.CoordinateGroup>
Expand Down
16 changes: 2 additions & 14 deletions src/features/Compute/CaseGroup/CaseRow/CaseRow.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
/* eslint-disable max-lines */
/* eslint-disable max-depth */
/* eslint-disable max-lines-per-function */
import { useMsal } from '@azure/msal-react';
import { useQuery } from '@tanstack/react-query';
import { useCallback, useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import {
AnalogueModelsService,
ComputeCaseDto,
CreateComputeCaseCommandResponse,
CreateComputeCaseInputSettingsForm,
Expand All @@ -17,7 +13,7 @@ import {
ModelAreaDto,
UpdateComputeCaseInputSettingsForm,
} from '../../../../api/generated';
import { useAccessToken } from '../../../../hooks/useAccessToken';
import { useFetchModel } from '../../../../hooks/useFetchModel';
import { CaseButtons } from '../CaseButtons/CaseButtons';
import { ModelAreaSelect } from '../CaseSettingSelects/ModelAreaSelect';
import { VariogramOptionSelect } from '../CaseSettingSelects/VariogramSettingSelect';
Expand Down Expand Up @@ -65,9 +61,6 @@ export const CaseRow = ({
name: string,
) => ListComputeSettingsMethodDto[] | undefined;
}) => {
const { modelId } = useParams<{ modelId: string }>();
const { instance, accounts } = useMsal();
const token = useAccessToken(instance, accounts[0]);
const [selectedModelArea, setModelArea] = useState<ModelAreaDto[]>();
const [selectedIndicatorParameters, setIndicatorParameters] =
useState<ListComputeSettingsInputValueDto[]>();
Expand All @@ -82,12 +75,7 @@ export const CaseRow = ({
const [saved, setSaved] = useState<boolean>(true);
const [caseError, setCaseError] = useState<string>('');

const { data } = useQuery({
queryKey: ['analogue-model', modelId],
queryFn: () =>
AnalogueModelsService.getApiAnalogueModels1(modelId as string),
enabled: !!token,
});
const { data } = useFetchModel();

const channelSettings = settingsFilter('Object');
const variogramSettings = settingsFilter('Variogram');
Expand Down
4 changes: 1 addition & 3 deletions src/features/ModelTable/ModelTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,10 @@ import { useAccessToken } from '../../hooks/useAccessToken';
import * as Styled from './ModelTable.styled';

export const ModelTable = ({
refetchKey,
progress,
activeUploadId,
transforming,
}: {
refetchKey: number;
progress: number;
activeUploadId: string;
transforming: boolean;
Expand All @@ -34,7 +32,7 @@ export const ModelTable = ({
const [toggle, setToggle] = useState<boolean>(false);
const [activeModel, setActiveModel] = useState<string>();
const { isLoading, data } = useQuery({
queryKey: ['analogue-models', refetchKey],
queryKey: ['analogue-models'],
queryFn: () => AnalogueModelsService.getApiAnalogueModels(),
enabled: !!token,
});
Expand Down
28 changes: 10 additions & 18 deletions src/features/ModelView/ModelMetadataView/ModelMetadataView.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
/* eslint-disable max-lines-per-function */
import { useMsal } from '@azure/msal-react';
import { Button, Table, Typography } from '@equinor/eds-core-react';
import { useMutation, useQuery } from '@tanstack/react-query';
import { useMutation } from '@tanstack/react-query';
import { useState } from 'react';
import { useParams } from 'react-router-dom';
import {
AddAnalogueDto,
AddAnalogueModelAnalogueCommandForm,
Expand All @@ -15,29 +13,18 @@ import {
AnalogueModelMetadataService,
AnalogueModelSourceType,
MetadataDto,
OpenAPI,
UpdateAnalogueModelCommandBody,
} from '../../../api/generated';
import { AnalogueModelsService } from '../../../api/generated/services/AnalogueModelsService';
import { useAccessToken } from '../../../hooks/useAccessToken';
import { queryClient } from '../../../auth/queryClient';
import { useFetchModel } from '../../../hooks/useFetchModel';
import { AddModelDialog } from '../../AddModel/AddModelDialog/AddModelDialog';
import { TableDataCell } from '../TableDataCell/TableDataCell';
import * as Styled from './ModelMetadataView.styled';

export const ModelMetadataView = () => {
const { modelId } = useParams();
const { instance, accounts } = useMsal();
const token = useAccessToken(instance, accounts[0]);
if (token) OpenAPI.TOKEN = token;

const [isAddModelDialog, setAddModelDialog] = useState<boolean>(false);
const [refetchKey, setRefetchKey] = useState<number>(0);
const { isLoading, data } = useQuery({
queryKey: ['analogue-model', modelId, refetchKey],
queryFn: () =>
AnalogueModelsService.getApiAnalogueModels1(modelId as string),
enabled: !!token,
});
const { isLoading, data } = useFetchModel();

const defaultMetadata: AnalogueModelDetail = {
analogueModelId: data?.data.analogueModelId
Expand Down Expand Up @@ -83,6 +70,9 @@ export const ModelMetadataView = () => {
requestBody,
);
},
onSuccess: () => {
queryClient.refetchQueries();
},
});

const uploadModelAnalouges = useMutation({
Expand All @@ -98,6 +88,9 @@ export const ModelMetadataView = () => {
requestBody,
);
},
onSuccess: () => {
queryClient.refetchQueries();
},
});

const metadataList: AddMetadataDto[] = [];
Expand Down Expand Up @@ -147,7 +140,6 @@ export const ModelMetadataView = () => {
requestBody: readyAnalogue,
});

setRefetchKey(refetchKey + 1);
toggleDialog();
};

Expand Down
23 changes: 3 additions & 20 deletions src/features/ModelView/ModelSourceView/ModelSourceView.tsx
Original file line number Diff line number Diff line change
@@ -1,27 +1,10 @@
import { useMsal } from '@azure/msal-react';
import { Table, Typography } from '@equinor/eds-core-react';
import { useQuery } from '@tanstack/react-query';
import { useParams } from 'react-router-dom';
import {
AnalogueModelsService,
OpenAPI,
UploadList,
} from '../../../api/generated';
import { useAccessToken } from '../../../hooks/useAccessToken';
import { UploadList } from '../../../api/generated';
import { useFetchModel } from '../../../hooks/useFetchModel';
import * as Styled from './ModelSourceView.styled';

export const ModelSourceView = () => {
const { modelId } = useParams();
const { instance, accounts } = useMsal();
const token = useAccessToken(instance, accounts[0]);
if (token) OpenAPI.TOKEN = token;

const { isLoading, data } = useQuery({
queryKey: ['analogue-model', modelId],
queryFn: () =>
AnalogueModelsService.getApiAnalogueModels1(modelId as string),
enabled: !!token,
});
const { isLoading, data } = useFetchModel();

if (isLoading || !data?.success) return <p>Loading ...</p>;

Expand Down
23 changes: 23 additions & 0 deletions src/hooks/useFetchCases.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { useQuery } from '@tanstack/react-query';

import { useMsal } from '@azure/msal-react';
import { useParams } from 'react-router-dom';
import { AnalogueModelComputeCasesService } from '../api/generated';
import { useAccessToken } from './useAccessToken';

export const useFetchCases = () => {
const { modelId } = useParams();
const { instance, accounts } = useMsal();
const token = useAccessToken(instance, accounts[0]);

const query = useQuery({
queryKey: ['model-cases', modelId],
queryFn: () =>
AnalogueModelComputeCasesService.getApiAnalogueModelsComputeCases(
modelId as string,
),
enabled: !!token,
});

return query;
};
22 changes: 22 additions & 0 deletions src/hooks/useFetchModel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { useQuery } from '@tanstack/react-query';
import { AnalogueModelsService } from '../api/generated/services/AnalogueModelsService';

import { useMsal } from '@azure/msal-react';
import { useParams } from 'react-router-dom';
import { useAccessToken } from './useAccessToken';

export const useFetchModel = (id?: string) => {
const { modelId } = useParams();
const { instance, accounts } = useMsal();
const token = useAccessToken(instance, accounts[0]);

const ID = id ? id : (modelId as string);

const query = useQuery({
queryKey: ['analogue-model', ID],
queryFn: () => AnalogueModelsService.getApiAnalogueModels1(ID),
enabled: !!token,
});

return query;
};
10 changes: 7 additions & 3 deletions src/pages/Browse/Browse.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
UploadFileType,
UploadsService,
} from '../../api/generated';
import { queryClient } from '../../auth/queryClient';
import { AddModelDialog } from '../../features/AddModel/AddModelDialog/AddModelDialog';
import { ModelTable } from '../../features/ModelTable/ModelTable';
import * as Styled from './Browse.styled';
Expand Down Expand Up @@ -48,7 +49,6 @@ export const Browse = () => {
const [uploadId, setUploadId] = useState<string>('');
const [isAddModelDialog, setAddModelDialog] = useState<boolean>(false);
const [uploadStatus, setUploadStatus] = useState<string>();
const [refetch, setRefetch] = useState<number>(0);
const [uploading, setUploading] = useState<boolean>(false);
const [transforming, setTransforming] = useState<boolean>(false);

Expand All @@ -67,6 +67,9 @@ export const Browse = () => {

const createModel = useMutation({
mutationFn: AnalogueModelsService.postApiAnalogueModels,
onSuccess: () => {
queryClient.refetchQueries({ queryKey: ['analogue-models'] });
},
});

const modelManifest = useMutation({
Expand All @@ -79,6 +82,9 @@ export const Browse = () => {

const uploadFinished = useMutation({
mutationFn: UploadsService.postApiUploadsModelsComplete,
onSuccess: () => {
queryClient.refetchQueries({ queryKey: ['analogue-models'] });
},
});

const convertModelFile = useMutation({
Expand Down Expand Up @@ -180,7 +186,6 @@ export const Browse = () => {
if (createModel.error === null && modelUpload.success) {
const id = modelUpload.data.analogueModelId;
setModelId(id);
setRefetch(refetch + 1);
setProgress(1);
uploadMetadata(id, metadata);

Expand Down Expand Up @@ -297,7 +302,6 @@ export const Browse = () => {
<Button onClick={toggleDialog}>Add new model</Button>
</div>
<ModelTable
refetchKey={refetch}
progress={progress}
activeUploadId={modelId}
transforming={transforming}
Expand Down
Loading