Skip to content

Commit

Permalink
♻️ refactor(react-query): update react query
Browse files Browse the repository at this point in the history
  • Loading branch information
thrownullexception committed Mar 30, 2024
1 parent 89fd8f1 commit 729d161
Show file tree
Hide file tree
Showing 40 changed files with 413 additions and 512 deletions.
263 changes: 58 additions & 205 deletions package-lock.json

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"bin": "./bin/dashpress",
"dependencies": {
"@dashpress/bacteria": "^0.0.12",
"@tanstack/react-query": "^5.28.9",
"@tanstack/react-table": "^8.7.9",
"bcrypt": "^5.0.1",
"change-case": "^4.1.2",
Expand Down Expand Up @@ -71,7 +72,6 @@
"react-final-form-arrays": "^3.1.4",
"react-hot-toast": "^2.2.0",
"react-paginate": "^8.1.3",
"react-query": "^3.39.2",
"react-quill": "^2.0.0",
"react-select": "^5.3.2",
"react-simple-code-editor": "^0.11.0",
Expand Down Expand Up @@ -102,19 +102,19 @@
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^14.2.1",
"@types/node": "^18.0.0",
"@types/react-dom": "^18.0.4",
"@types/cryptr": "^4.0.1",
"@types/formidable": "^3.4.5",
"@types/jsonwebtoken": "^8.5.8",
"@types/lodash": "^4.14.182",
"@types/microseconds": "^0.2.0",
"@types/node": "^18.0.0",
"@types/nodemailer": "^6.4.6",
"@types/prismjs": "^1.26.0",
"@types/qs": "^6.9.7",
"@types/ramda": "0.27.40",
"@types/react": "^18.0.11",
"@types/react-datepicker": "^4.4.1",
"@types/react-dom": "^18.0.4",
"@typescript-eslint/eslint-plugin": "^5.31.0",
"@typescript-eslint/parser": "^5.31.0",
"babel-loader": "^8.2.5",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import fetchMock from "jest-fetch-mock";
import { QueryClient, QueryClientProvider } from "react-query";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { waitFor } from "@testing-library/react";
import { FieldQueryFilter, FilterOperators } from "shared/types/data";
import { renderHook } from "__tests__/_/lib/renderHook";
Expand Down
120 changes: 59 additions & 61 deletions src/frontend/components/FEPaginationTable/useFEPagination.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useQuery, UseQueryResult } from "react-query";
import { useQuery, UseQueryResult } from "@tanstack/react-query";
import {
FieldQueryFilter,
FilterOperators,
Expand All @@ -18,72 +18,70 @@ export function useFEPagination<T>(
endPoint: string,
dataState: IPaginatedDataState<T>
): UseQueryResult<PaginatedData<T>> {
return useQuery<PaginatedData<T>>(
getQueryCachekey(endPoint),
async () => {
return useQuery<PaginatedData<T>>({
queryKey: getQueryCachekey(endPoint),
queryFn: async () => {
return await makeGetRequest(endPoint, "Data could not be retrieved");
},
{
select: (data: any) => {
let returnData: T[] = data as unknown as T[];
if (dataState.filters) {
returnData = returnData.filter((datum) => {
return dataState.filters.every(($filter) => {
const filter = $filter as unknown as FieldQueryFilter;
const filterValue = filter.value.value;
const currentValue = datum[filter.id];
if (!filterValue) {
return true;
}
switch (filter.value.operator) {
case FilterOperators.CONTAINS:
return currentValue
.toLowerCase()
.includes((filterValue as string).toLowerCase());
case FilterOperators.EQUAL_TO:
return currentValue === filterValue;
case FilterOperators.NOT_EQUAL:
return currentValue !== filterValue;
case FilterOperators.LESS_THAN:
return currentValue < filterValue;
case FilterOperators.GREATER_THAN:
return currentValue > filterValue;
case FilterOperators.IN:
return (filterValue as string[]).includes(currentValue);
case FilterOperators.NOT_IN:
return !(filterValue as string[]).includes(currentValue);
}
select: (data: any) => {
let returnData: T[] = data as unknown as T[];
if (dataState.filters) {
returnData = returnData.filter((datum) => {
return dataState.filters.every(($filter) => {
const filter = $filter as unknown as FieldQueryFilter;
const filterValue = filter.value.value;
const currentValue = datum[filter.id];
if (!filterValue) {
return true;
});
}
switch (filter.value.operator) {
case FilterOperators.CONTAINS:
return currentValue
.toLowerCase()
.includes((filterValue as string).toLowerCase());
case FilterOperators.EQUAL_TO:
return currentValue === filterValue;
case FilterOperators.NOT_EQUAL:
return currentValue !== filterValue;
case FilterOperators.LESS_THAN:
return currentValue < filterValue;
case FilterOperators.GREATER_THAN:
return currentValue > filterValue;
case FilterOperators.IN:
return (filterValue as string[]).includes(currentValue);
case FilterOperators.NOT_IN:
return !(filterValue as string[]).includes(currentValue);
}
return true;
});
}
});
}

if (dataState.sortBy && dataState.sortBy.length > 0) {
const { id, desc } = dataState.sortBy[0];
if (dataState.sortBy && dataState.sortBy.length > 0) {
const { id, desc } = dataState.sortBy[0];

returnData = returnData.sort((a, b) => {
const value1 = (desc ? b : a)[id];
const value2 = (desc ? a : b)[id];
if (typeof value1 === "number") {
return compareNumbers(value1, value2);
}
returnData = returnData.sort((a, b) => {
const value1 = (desc ? b : a)[id];
const value2 = (desc ? a : b)[id];
if (typeof value1 === "number") {
return compareNumbers(value1, value2);
}

return compareString(value1, value2);
});
}
const totalReturnData = returnData.length;
const pageSize = dataState.pageSize || DEFAULT_PAGE_SIZE;
return compareString(value1, value2);
});
}
const totalReturnData = returnData.length;
const pageSize = dataState.pageSize || DEFAULT_PAGE_SIZE;

return {
pageIndex: dataState.pageIndex,
pageSize,
totalRecords: totalReturnData,
data: returnData.slice(
(dataState.pageIndex - 1) * pageSize,
dataState.pageIndex * pageSize
),
};
},
}
);
return {
pageIndex: dataState.pageIndex,
pageSize,
totalRecords: totalReturnData,
data: returnData.slice(
(dataState.pageIndex - 1) * pageSize,
dataState.pageIndex * pageSize
),
};
},
});
}
8 changes: 4 additions & 4 deletions src/frontend/design-system/components/Table/Stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ Empty.args = {
},
isLoading: false,
error: false,
isPreviousData: false,
isPlaceholderData: false,
},
};

Expand All @@ -102,7 +102,7 @@ Error.args = {
},
isLoading: false,
error: "Some Error Occured",
isPreviousData: false,
isPlaceholderData: false,
},
};

Expand All @@ -117,14 +117,14 @@ Loading.args = {
},
isLoading: true,
error: false,
isPreviousData: false,
isPlaceholderData: false,
},
};

export const PreviousData = Template.bind({});
PreviousData.args = {
tableData: {
...TABLE_DATA,
isPreviousData: true,
isPlaceholderData: true,
},
};
2 changes: 1 addition & 1 deletion src/frontend/design-system/components/Table/data/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export const TABLE_DATA = {
},
isLoading: false,
error: false,
isPreviousData: false,
isPlaceholderData: false,
};

export const TABLE_COLUMNS: ITableColumn[] = [
Expand Down
4 changes: 2 additions & 2 deletions src/frontend/design-system/components/Table/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export function Table<T extends unknown>({
},
isLoading,
error,
isPreviousData,
isPlaceholderData,
} = tableData;

const totalPageCount = getPageCount(data.totalRecords, data.pageSize);
Expand Down Expand Up @@ -111,7 +111,7 @@ export function Table<T extends unknown>({
return <TableSkeleton lean={lean} />;
}

const previousDataRender = isPreviousData ? (
const previousDataRender = isPlaceholderData ? (
<BaseSkeleton
height="2px"
width="100%"
Expand Down
4 changes: 2 additions & 2 deletions src/frontend/design-system/components/Table/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { HeaderContext } from "@tanstack/react-table";
import { ReactNode } from "react";
import { UseQueryResult } from "react-query";
import { UseQueryResult } from "@tanstack/react-query";
import {
IPaginatedDataState,
PaginatedData,
Expand All @@ -27,7 +27,7 @@ export interface ITableProps<T> {
columns: ITableColumn[];
tableData: Pick<
UseQueryResult<PaginatedData<Record<string, unknown>>, unknown>,
"data" | "isLoading" | "error" | "isPreviousData"
"data" | "isLoading" | "error" | "isPlaceholderData"
>;
lean?: true;
border?: boolean;
Expand Down
17 changes: 10 additions & 7 deletions src/frontend/hooks/auth/preferences.store.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useMutation } from "react-query";
import { useMutation } from "@tanstack/react-query";
import { makeActionRequest } from "frontend/lib/data/makeRequest";
import { useStorageApi } from "frontend/lib/data/useApi";
import { useWaitForResponseMutationOptions } from "frontend/lib/data/useMutate/useWaitForResponseMutationOptions";
Expand Down Expand Up @@ -55,10 +55,13 @@ export function useUpsertUserPreferenceMutation<T extends UserPreferencesKeys>(
successMessage: MAKE_USER_PREFERENCE_CRUD_CONFIG(key).MUTATION_LANG.SAVED,
});

return useMutation(async (values: UserPreferencesValueType<T>) => {
await makeActionRequest("PUT", userPrefrencesApiPath(key), {
data: values,
});
return values;
}, apiMutateOptions);
return useMutation({
mutationFn: async (values: UserPreferencesValueType<T>) => {
await makeActionRequest("PUT", userPrefrencesApiPath(key), {
data: values,
});
return values;
},
...apiMutateOptions,
});
}
17 changes: 10 additions & 7 deletions src/frontend/hooks/configuration/configuration.store.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useMutation } from "react-query";
import { useMutation } from "@tanstack/react-query";
import {
APP_CONFIGURATION_CONFIG,
AppConfigurationKeys,
Expand Down Expand Up @@ -95,10 +95,13 @@ export function useUpsertConfigurationMutation<T extends AppConfigurationKeys>(
successMessage: MAKE_APP_CONFIGURATION_CRUD_CONFIG(key).MUTATION_LANG.SAVED,
});

return useMutation(async (values: AppConfigurationValueType<T>) => {
await makeActionRequest("PUT", configurationApiPath(key, entity, "PUT"), {
data: values,
});
return values;
}, apiMutateOptions);
return useMutation({
mutationFn: async (values: AppConfigurationValueType<T>) => {
await makeActionRequest("PUT", configurationApiPath(key, entity, "PUT"), {
data: values,
});
return values;
},
...apiMutateOptions,
});
}
29 changes: 15 additions & 14 deletions src/frontend/hooks/data/data.store.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import qs from "qs";
import { useRouter } from "next/router";
import { useMutation } from "react-query";
import { useMutation } from "@tanstack/react-query";
import { FieldQueryFilter, FilterOperators } from "shared/types/data";
import { CRUD_CONFIG_NOT_FOUND } from "frontend/lib/crud-config";
import { makeActionRequest } from "frontend/lib/data/makeRequest";
Expand Down Expand Up @@ -38,7 +38,7 @@ export const useEntityDataDetails = ({
ENTITY_DETAILS_PATH({ entity, entityId, column }),
{
errorMessage: entityCrudConfig.TEXT_LANG.NOT_FOUND,
enabled: column !== SYSTEM_LOADING_VALUE,
enabled: column !== SYSTEM_LOADING_VALUE && !!entityId,
defaultData: {},
}
);
Expand Down Expand Up @@ -129,6 +129,7 @@ export const useEntityReferenceCount = (
export const useEntityDataReference = (entity: string, entityId: string) => {
return useApi<string>(ENTITY_REFERENCE_PATH({ entity, entityId }), {
errorMessage: CRUD_CONFIG_NOT_FOUND("Reference data"),
enabled: !!entityId && !!entity,
defaultData: "",
});
};
Expand Down Expand Up @@ -160,11 +161,11 @@ export function useEntityDataCreationMutation(
}),
});

return useMutation(
async (data: Record<string, string>) =>
return useMutation({
mutationFn: async (data: Record<string, string>) =>
await makeActionRequest("POST", `/api/data/${entity}`, { data }),
apiMutateOptions
);
...apiMutateOptions,
});
}

export function useEntityDataUpdationMutation(
Expand All @@ -184,13 +185,13 @@ export function useEntityDataUpdationMutation(

const metadata = useEntityMetadataDetails({ entity, entityId });

return useMutation(
async (data: Record<string, string>) =>
return useMutation({
mutationFn: async (data: Record<string, string>) =>
await makeActionRequest("PATCH", `/api/data/${entity}/${entityId}`, {
data: { ...data, ...metadata },
}),
apiMutateOptions
);
...apiMutateOptions,
});
}

export function useEntityDataDeletionMutation(
Expand Down Expand Up @@ -220,9 +221,9 @@ export function useEntityDataDeletionMutation(
successMessage: entityCrudConfig.MUTATION_LANG.DELETE,
});
// eyes on optimstic delete here
return useMutation(
async (id: string) =>
return useMutation({
mutationFn: async (id: string) =>
await makeActionRequest("DELETE", `/api/data/${entity}/${id}`),
apiMutateOptions
);
...apiMutateOptions,
});
}
6 changes: 5 additions & 1 deletion src/frontend/lib/data/QueryClient.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import React, { ReactNode } from "react";
import { QueryClientProvider, QueryClient, QueryCache } from "react-query";
import {
QueryClientProvider,
QueryClient,
QueryCache,
} from "@tanstack/react-query";

export const queryCache = new QueryCache();

Expand Down
Loading

0 comments on commit 729d161

Please sign in to comment.