You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "justinpark (via GitHub)" <gi...@apache.org> on 2023/04/20 22:50:04 UTC

[GitHub] [superset] justinpark opened a new pull request, #23760: [chore] Refactor react-query by redux-toolkit query

justinpark opened a new pull request, #23760:
URL: https://github.com/apache/superset/pull/23760

   ### SUMMARY
   
   As a follow-up of [discussion](https://github.com/apache/superset/pull/23488#pullrequestreview-1379337190), this commit migrates the existing react-query api to redux-toolkit query.
   
   tl;dr
   
   > In order to consolidate the multiple state management solution, superset team decided to leverage the redux with toolkit in order to organize the existing redux state.
   > Redux toolkit also includes the rdk query package which can replace the existing react-query hooks (which is a similar solution to minimize the state of async api request) with a single solution.
   
   ### BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
   N/A
   
   ### TESTING INSTRUCTIONS
   test all sqllab functions that runs as expected before
   
   ### ADDITIONAL INFORMATION
   - [ ] Has associated issue: #23460 #23488
   - [ ] Required feature flags:
   - [ ] Changes UI
   - [ ] Includes DB Migration (follow approval process in [SIP-59](https://github.com/apache/superset/issues/13351))
     - [ ] Migration is atomic, supports rollback & is backwards-compatible
     - [ ] Confirm DB migration upgrade and downgrade tested
     - [ ] Runtime estimates and downtime expectations provided
   - [x] Introduces new feature or API
   - [x] Removes existing feature or API
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] codecov[bot] commented on pull request #23760: chore(sqllab): Refactor react-query by redux-toolkit query

Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #23760:
URL: https://github.com/apache/superset/pull/23760#issuecomment-1517277726

   ## [Codecov](https://codecov.io/gh/apache/superset/pull/23760?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) Report
   > Merging [#23760](https://codecov.io/gh/apache/superset/pull/23760?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) (6df3c89) into [master](https://codecov.io/gh/apache/superset/commit/5bec1a65ae3bdae91ee3af8ec3d70b1647726d98?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) (5bec1a6) will **decrease** coverage by `0.24%`.
   > The diff coverage is `16.83%`.
   
   > :exclamation: Current head 6df3c89 differs from pull request most recent head 9dda4c6. Consider uploading reports for the commit 9dda4c6 to get more accurate results
   
   ```diff
   @@            Coverage Diff             @@
   ##           master   #23760      +/-   ##
   ==========================================
   - Coverage   68.08%   67.85%   -0.24%     
   ==========================================
     Files        1923     1924       +1     
     Lines       74135    74399     +264     
     Branches     8103     8123      +20     
   ==========================================
   + Hits        50478    50483       +5     
   - Misses      21580    21827     +247     
   - Partials     2077     2089      +12     
   ```
   
   | Flag | Coverage Δ | |
   |---|---|---|
   | javascript | `54.14% <68.57%> (+0.03%)` | :arrow_up: |
   | postgres | `?` | |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#carryforward-flags-in-the-pull-request-comment) to find out more.
   
   | [Impacted Files](https://codecov.io/gh/apache/superset/pull/23760?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) | Coverage Δ | |
   |---|---|---|
   | [superset-frontend/src/SqlLab/App.jsx](https://codecov.io/gh/apache/superset/pull/23760?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c3VwZXJzZXQtZnJvbnRlbmQvc3JjL1NxbExhYi9BcHAuanN4) | `0.00% <0.00%> (ø)` | |
   | [...et-frontend/src/components/TableSelector/index.tsx](https://codecov.io/gh/apache/superset/pull/23760?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c3VwZXJzZXQtZnJvbnRlbmQvc3JjL2NvbXBvbmVudHMvVGFibGVTZWxlY3Rvci9pbmRleC50c3g=) | `81.08% <ø> (+2.70%)` | :arrow_up: |
   | [superset-frontend/src/views/App.tsx](https://codecov.io/gh/apache/superset/pull/23760?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c3VwZXJzZXQtZnJvbnRlbmQvc3JjL3ZpZXdzL0FwcC50c3g=) | `0.00% <0.00%> (ø)` | |
   | [superset-frontend/src/views/store.ts](https://codecov.io/gh/apache/superset/pull/23760?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c3VwZXJzZXQtZnJvbnRlbmQvc3JjL3ZpZXdzL3N0b3JlLnRz) | `78.26% <ø> (ø)` | |
   | [superset/cli/main.py](https://codecov.io/gh/apache/superset/pull/23760?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c3VwZXJzZXQvY2xpL21haW4ucHk=) | `0.00% <0.00%> (ø)` | |
   | [superset/cli/native\_filters.py](https://codecov.io/gh/apache/superset/pull/23760?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c3VwZXJzZXQvY2xpL25hdGl2ZV9maWx0ZXJzLnB5) | `0.00% <0.00%> (ø)` | |
   | [...uperset/utils/dashboard\_filter\_scopes\_converter.py](https://codecov.io/gh/apache/superset/pull/23760?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c3VwZXJzZXQvdXRpbHMvZGFzaGJvYXJkX2ZpbHRlcl9zY29wZXNfY29udmVydGVyLnB5) | `15.78% <2.70%> (-21.42%)` | :arrow_down: |
   | [...uperset-frontend/src/hooks/apiResources/schemas.ts](https://codecov.io/gh/apache/superset/pull/23760?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c3VwZXJzZXQtZnJvbnRlbmQvc3JjL2hvb2tzL2FwaVJlc291cmNlcy9zY2hlbWFzLnRz) | `61.53% <62.50%> (-30.77%)` | :arrow_down: |
   | [superset-frontend/src/hooks/apiResources/tables.ts](https://codecov.io/gh/apache/superset/pull/23760?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c3VwZXJzZXQtZnJvbnRlbmQvc3JjL2hvb2tzL2FwaVJlc291cmNlcy90YWJsZXMudHM=) | `70.58% <68.96%> (-13.63%)` | :arrow_down: |
   | [...frontend/src/components/DatabaseSelector/index.tsx](https://codecov.io/gh/apache/superset/pull/23760?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c3VwZXJzZXQtZnJvbnRlbmQvc3JjL2NvbXBvbmVudHMvRGF0YWJhc2VTZWxlY3Rvci9pbmRleC50c3g=) | `91.52% <100.00%> (ø)` | |
   | ... and [2 more](https://codecov.io/gh/apache/superset/pull/23760?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) | |
   
   ... and [15 files with indirect coverage changes](https://codecov.io/gh/apache/superset/pull/23760/indirect-changes?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation)
   
   :mega: We’re building smart automated test selection to slash your CI/CD build times. [Learn more](https://about.codecov.io/iterative-testing/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation)
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] justinpark commented on a diff in pull request #23760: chore(sqllab): Refactor react-query by redux-toolkit query

Posted by "justinpark (via GitHub)" <gi...@apache.org>.
justinpark commented on code in PR #23760:
URL: https://github.com/apache/superset/pull/23760#discussion_r1180753350


##########
superset-frontend/src/hooks/apiResources/schemas.ts:
##########
@@ -16,65 +16,97 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-import { useRef } from 'react';
-import { useQuery, UseQueryOptions } from 'react-query';
-import rison from 'rison';
-import { SupersetClient } from '@superset-ui/core';
-
-export type FetchSchemasQueryParams = {
-  dbId?: string | number;
-  forceRefresh?: boolean;
-};
-
-type QueryData = {
-  json: { result: string[] };
-  response: Response;
-};
+import { useCallback, useEffect, useRef } from 'react';
+import { api, JsonResponse } from './queryApi';
 
 export type SchemaOption = {
   value: string;
   label: string;
   title: string;
 };
 
-export function fetchSchemas({ dbId, forceRefresh }: FetchSchemasQueryParams) {
-  const queryParams = rison.encode({ force: forceRefresh });
-  // TODO: Would be nice to add pagination in a follow-up. Needs endpoint changes.
-  const endpoint = `/api/v1/database/${dbId}/schemas/?q=${queryParams}`;
-  return SupersetClient.get({ endpoint }) as Promise<QueryData>;
-}
+export type FetchSchemasQueryParams = {
+  dbId?: string | number;
+  forceRefresh: boolean;
+  onSuccess?: (data: SchemaOption[], isRefetched: boolean) => void;
+  onError?: () => void;
+};
+
+type Params = Omit<FetchSchemasQueryParams, 'forceRefresh'>;
+
+const schemaApi = api.injectEndpoints({
+  endpoints: builder => ({
+    schemas: builder.query<SchemaOption[], FetchSchemasQueryParams>({
+      providesTags: [{ type: 'Schemas', id: 'LIST' }],
+      query: ({ dbId, forceRefresh }) => ({
+        endpoint: `/api/v1/database/${dbId}/schemas/`,
+        // TODO: Would be nice to add pagination in a follow-up. Needs endpoint changes.
+        urlParams: {
+          force: forceRefresh,
+        },
+        transformResponse: ({ json }: JsonResponse) =>
+          json.result.map((value: string) => ({
+            value,
+            label: value,
+            title: value,
+          })),
+      }),
+      serializeQueryArgs: ({ queryArgs: { dbId } }) => ({
+        dbId,
+      }),
+    }),
+  }),
+});
 
-type Params = FetchSchemasQueryParams &
-  Pick<UseQueryOptions<SchemaOption[]>, 'onSuccess' | 'onError'>;
+export const { useLazySchemasQuery, useSchemasQuery } = schemaApi;
+
+const EMPTY_SCHEMAS = [] as SchemaOption[];
 
 export function useSchemas(options: Params) {
+  const isMountedRef = useRef(false);
   const { dbId, onSuccess, onError } = options || {};
-  const forceRefreshRef = useRef(false);
-  const params = { dbId };
-  const result = useQuery<QueryData, Error, SchemaOption[]>(
-    ['schemas', { dbId }],
-    () => fetchSchemas({ ...params, forceRefresh: forceRefreshRef.current }),
+  const [trigger, refetchResult] = useLazySchemasQuery();
+  const result = useSchemasQuery(
+    { dbId, forceRefresh: false },
     {
-      select: ({ json }) =>
-        json.result.map((value: string) => ({
-          value,
-          label: value,
-          title: value,
-        })),
-      enabled: Boolean(dbId),
-      onSuccess,
-      onError,
-      onSettled: () => {
-        forceRefreshRef.current = false;
-      },
+      skip: !dbId,
     },
   );
 
+  const refetch = useCallback(() => {
+    if (dbId) {
+      trigger({ dbId, forceRefresh: true }).then(
+        ({ isSuccess, isError, data }) => {
+          if (isSuccess) {
+            onSuccess?.(data || EMPTY_SCHEMAS, true);
+          }
+          if (isError) {
+            onError?.();
+          }
+        },
+      );
+    }
+  }, [dbId]);
+
+  useEffect(() => {
+    if (isMountedRef.current) {
+      const { requestId, isSuccess, isError, isFetching, data, originalArgs } =
+        result;
+      if (!originalArgs?.forceRefresh && requestId && !isFetching) {
+        if (isSuccess) {
+          onSuccess?.(data || EMPTY_SCHEMAS, false);
+        }
+        if (isError) {
+          onError?.();
+        }
+      }
+    } else {
+      isMountedRef.current = true;
+    }
+  }, [result]);

Review Comment:
   waiting #23871 to clean up dependency warning



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] michael-s-molina commented on a diff in pull request #23760: chore(sqllab): Refactor react-query by redux-toolkit query

Posted by "michael-s-molina (via GitHub)" <gi...@apache.org>.
michael-s-molina commented on code in PR #23760:
URL: https://github.com/apache/superset/pull/23760#discussion_r1177774918


##########
superset-frontend/spec/helpers/testing-library.tsx:
##########
@@ -64,11 +71,18 @@ export function createWrapper(options?: Options) {
     if (useRedux) {
       const mockStore =
         store ??
-        configureStore({
-          preloadedState: initialState || {},
-          devTools: false,
-          reducer: reducers || reducerIndex,
-        });
+        (!initialState

Review Comment:
   Just a nit but you could invert the order and not negate the condition:
   
   `initialState ? configureStore : storeWithApi`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] justinpark commented on a diff in pull request #23760: chore(sqllab): Refactor react-query by redux-toolkit query

Posted by "justinpark (via GitHub)" <gi...@apache.org>.
justinpark commented on code in PR #23760:
URL: https://github.com/apache/superset/pull/23760#discussion_r1179756195


##########
superset-frontend/src/hooks/apiResources/tables.test.ts:
##########
@@ -108,19 +109,20 @@ describe('useTables hook', () => {
         })}`,
       ).length,
     ).toBe(1);
-    expect(result.current.data).toEqual(expectedData);
-    await act(async () => {
+    act(() => {

Review Comment:
   yes. it's recommended. it throws the following warning without this `act` wrapper
   
   ```
     console.error
       Warning: An update to TestComponent inside a test was not wrapped in act(...).
   
       When testing, code that causes React state updates should be wrapped into act(...):
   
       act(() => {
         /* fire events that update state */
       });
       /* assert on the output */
   
       This ensures that you're testing the behavior the user would see in the browser. Learn more at https://fb.me/react-wrap-tests-with-act
           in TestComponent
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] justinpark merged pull request #23760: chore(sqllab): Refactor react-query by redux-toolkit query

Posted by "justinpark (via GitHub)" <gi...@apache.org>.
justinpark merged PR #23760:
URL: https://github.com/apache/superset/pull/23760


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] michael-s-molina commented on a diff in pull request #23760: chore(sqllab): Refactor react-query by redux-toolkit query

Posted by "michael-s-molina (via GitHub)" <gi...@apache.org>.
michael-s-molina commented on code in PR #23760:
URL: https://github.com/apache/superset/pull/23760#discussion_r1173755420


##########
superset-frontend/src/SqlLab/components/SqlEditorLeftBar/SqlEditorLeftBar.test.jsx:
##########
@@ -37,11 +38,32 @@ const mockedProps = {
   },
   height: 0,
 };
-const middlewares = [thunk];
-const mockStore = configureStore(middlewares);
-const store = mockStore(initialState);
+
+let store;
+let actions;
+
+const logAction = () => next => action => {
+  if (typeof action === 'function') {
+    return next(action);
+  }
+
+  actions.push(action);
+

Review Comment:
   ```suggestion
   ```



##########
superset-frontend/spec/helpers/testing-library.tsx:
##########
@@ -81,8 +95,8 @@ export function createWrapper(options?: Options) {
       result = <BrowserRouter>{result}</BrowserRouter>;
     }
 
-    if (useQuery) {
-      result = <QueryProvider>{result}</QueryProvider>;
+    if (useQuery && !useRedux) {

Review Comment:
   Previously, the developer had the option to use query params without Redux. Now it's a little bit weird because you are setting `useQuery` and the store is being configured underneath. `useQuery` is more related to the URL query params than Redux. Could you separate the concepts again?



##########
superset-frontend/src/SqlLab/components/SqlEditorLeftBar/SqlEditorLeftBar.test.jsx:
##########
@@ -37,11 +38,32 @@ const mockedProps = {
   },
   height: 0,
 };
-const middlewares = [thunk];
-const mockStore = configureStore(middlewares);
-const store = mockStore(initialState);
+
+let store;
+let actions;
+
+const logAction = () => next => action => {
+  if (typeof action === 'function') {
+    return next(action);
+  }
+

Review Comment:
   ```suggestion
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] michael-s-molina commented on a diff in pull request #23760: chore(sqllab): Refactor react-query by redux-toolkit query

Posted by "michael-s-molina (via GitHub)" <gi...@apache.org>.
michael-s-molina commented on code in PR #23760:
URL: https://github.com/apache/superset/pull/23760#discussion_r1184878372


##########
superset-frontend/spec/helpers/testing-library.tsx:
##########
@@ -26,26 +26,33 @@ import { DndProvider } from 'react-dnd';
 import { HTML5Backend } from 'react-dnd-html5-backend';
 import reducerIndex from 'spec/helpers/reducerIndex';
 import { QueryParamProvider } from 'use-query-params';
-import QueryProvider from 'src/views/QueryProvider';
 import { configureStore, Store } from '@reduxjs/toolkit';
+import { api } from 'src/hooks/apiResources/queryApi';
 
 type Options = Omit<RenderOptions, 'queries'> & {
   useRedux?: boolean;
   useDnd?: boolean;
   useQueryParams?: boolean;
   useRouter?: boolean;
-  useQuery?: boolean;
   initialState?: {};
   reducers?: {};
   store?: Store;
 };
 
+export const storeWithApi = configureStore({
+  reducer: {
+    [api.reducerPath]: api.reducer,
+  },
+  middleware: getDefaultMiddleware =>
+    getDefaultMiddleware().concat(api.middleware),
+  devTools: false,
+});

Review Comment:
   ```suggestion
   const createStore = (initialState: object = {}, reducers: object = {}) =>
     configureStore({
       preloadedState: initialState,
       reducer: {
         ...(reducers || reducerIndex),
         [api.reducerPath]: api.reducer,
       },
       middleware: getDefaultMiddleware =>
         getDefaultMiddleware().concat(api.middleware),
       devTools: false,
     });
   
   export const defaultStore = createStore();
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] michael-s-molina commented on a diff in pull request #23760: chore(sqllab): Refactor react-query by redux-toolkit query

Posted by "michael-s-molina (via GitHub)" <gi...@apache.org>.
michael-s-molina commented on code in PR #23760:
URL: https://github.com/apache/superset/pull/23760#discussion_r1174614713


##########
superset-frontend/spec/helpers/testing-library.tsx:
##########
@@ -81,8 +95,8 @@ export function createWrapper(options?: Options) {
       result = <BrowserRouter>{result}</BrowserRouter>;
     }
 
-    if (useQuery) {
-      result = <QueryProvider>{result}</QueryProvider>;
+    if (useApi && !useRedux) {

Review Comment:
   What's the difference between `useRedux` and `useApi`? Looking at the code, the middleware and api reducer are also set when `useRedux` is true. Can we consolidate and use only `useRedux`?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] justinpark commented on a diff in pull request #23760: chore(sqllab): Refactor react-query by redux-toolkit query

Posted by "justinpark (via GitHub)" <gi...@apache.org>.
justinpark commented on code in PR #23760:
URL: https://github.com/apache/superset/pull/23760#discussion_r1179756195


##########
superset-frontend/src/hooks/apiResources/tables.test.ts:
##########
@@ -108,19 +109,20 @@ describe('useTables hook', () => {
         })}`,
       ).length,
     ).toBe(1);
-    expect(result.current.data).toEqual(expectedData);
-    await act(async () => {
+    act(() => {

Review Comment:
   yes. it's recommended.
   
   ```
     console.error
       Warning: An update to TestComponent inside a test was not wrapped in act(...).
   
       When testing, code that causes React state updates should be wrapped into act(...):
   
       act(() => {
         /* fire events that update state */
       });
       /* assert on the output */
   
       This ensures that you're testing the behavior the user would see in the browser. Learn more at https://fb.me/react-wrap-tests-with-act
           in TestComponent
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] justinpark commented on a diff in pull request #23760: chore(sqllab): Refactor react-query by redux-toolkit query

Posted by "justinpark (via GitHub)" <gi...@apache.org>.
justinpark commented on code in PR #23760:
URL: https://github.com/apache/superset/pull/23760#discussion_r1179742309


##########
superset-frontend/src/hooks/apiResources/tables.ts:
##########
@@ -84,32 +93,60 @@ export function useTables(options: Params) {
     [schemaOptions],
   );
   const { dbId, schema, onSuccess, onError } = options || {};
-  const forceRefreshRef = useRef(false);
-  const params = { dbId, schema };
-  const result = useQuery<QueryData, Error, Data>(
-    ['tables', { dbId, schema }],
-    () => fetchTables({ ...params, forceRefresh: forceRefreshRef.current }),
+
+  const enabled = Boolean(
+    dbId && schema && !isFetching && schemaOptionsMap.has(schema),
+  );
+
+  const result = useTablesQuery(
+    { dbId, schema, forceRefresh: false },
     {
-      select: ({ json }) => ({
-        options: json.result,
-        hasMore: json.count > json.result.length,
-      }),
-      enabled: Boolean(
-        dbId && schema && !isFetching && schemaOptionsMap.has(schema),
-      ),
-      onSuccess,
-      onError,
-      onSettled: () => {
-        forceRefreshRef.current = false;
-      },
+      skip: !enabled,
     },
   );
+  const [trigger] = useLazyTablesQuery();
+
+  const refetch = useCallback(() => {
+    if (enabled) {
+      trigger({ dbId, schema, forceRefresh: true }).then(
+        ({ isSuccess, isError, data, error }) => {
+          if (isSuccess && data) {
+            onSuccess?.(data, true);
+          }
+          if (isError) {
+            onError?.(error as Response);
+          }
+        },
+      );
+    }
+  }, [dbId, schema, enabled]);
+
+  useEffect(() => {
+    if (isMountedRef.current) {

Review Comment:
   good call. I need to add `isMountedRef` on `schemas` api too



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] michael-s-molina commented on a diff in pull request #23760: chore(sqllab): Refactor react-query by redux-toolkit query

Posted by "michael-s-molina (via GitHub)" <gi...@apache.org>.
michael-s-molina commented on code in PR #23760:
URL: https://github.com/apache/superset/pull/23760#discussion_r1178125481


##########
superset-frontend/src/hooks/apiResources/queryApi.test.ts:
##########
@@ -0,0 +1,104 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import fetchMock from 'fetch-mock';
+import configureStore, { MockStore } from 'redux-mock-store';
+import rison from 'rison';
+import { JsonResponse } from '@superset-ui/core';
+import { supersetClientQuery } from './queryApi';
+
+const getBaseQueryApiMock = (store: MockStore) => ({
+  ...new AbortController(),
+  dispatch: store.dispatch,
+  getState: store.getState,
+  extra: undefined,
+  endpoint: 'endpoint',
+  type: 'query' as const,
+});
+
+describe('queryApi', () => {

Review Comment:
   Could you avoid using `describe`? Check this [guideline](https://github.com/apache/superset/wiki/Testing-Guidelines-and-Best-Practices#avoid-nesting-when-youre-testing)



##########
superset-frontend/src/hooks/apiResources/tables.test.ts:
##########
@@ -108,19 +109,20 @@ describe('useTables hook', () => {
         })}`,
       ).length,
     ).toBe(1);
-    expect(result.current.data).toEqual(expectedData);
-    await act(async () => {
+    act(() => {

Review Comment:
   Do you need this `act`? Won't the next `await` already be sufficient?



##########
superset-frontend/src/hooks/apiResources/tables.ts:
##########
@@ -84,32 +93,60 @@ export function useTables(options: Params) {
     [schemaOptions],
   );
   const { dbId, schema, onSuccess, onError } = options || {};
-  const forceRefreshRef = useRef(false);
-  const params = { dbId, schema };
-  const result = useQuery<QueryData, Error, Data>(
-    ['tables', { dbId, schema }],
-    () => fetchTables({ ...params, forceRefresh: forceRefreshRef.current }),
+
+  const enabled = Boolean(
+    dbId && schema && !isFetching && schemaOptionsMap.has(schema),
+  );
+
+  const result = useTablesQuery(
+    { dbId, schema, forceRefresh: false },
     {
-      select: ({ json }) => ({
-        options: json.result,
-        hasMore: json.count > json.result.length,
-      }),
-      enabled: Boolean(
-        dbId && schema && !isFetching && schemaOptionsMap.has(schema),
-      ),
-      onSuccess,
-      onError,
-      onSettled: () => {
-        forceRefreshRef.current = false;
-      },
+      skip: !enabled,
     },
   );
+  const [trigger] = useLazyTablesQuery();
+
+  const refetch = useCallback(() => {
+    if (enabled) {
+      trigger({ dbId, schema, forceRefresh: true }).then(
+        ({ isSuccess, isError, data, error }) => {
+          if (isSuccess && data) {
+            onSuccess?.(data, true);
+          }
+          if (isError) {
+            onError?.(error as Response);
+          }
+        },
+      );
+    }
+  }, [dbId, schema, enabled]);
+
+  useEffect(() => {
+    if (isMountedRef.current) {

Review Comment:
   Why do you need this ref here but not in the `schemas` api?



##########
superset-frontend/src/hooks/apiResources/tables.test.ts:
##########
@@ -191,58 +191,77 @@ describe('useTables hook', () => {
     fetchMock.get(`glob:*/api/v1/database/${expectDbId}/schemas/*`, {
       result: fakeSchemaApiResult,
     });
-    const { result, rerender } = renderHook(
+    const { result, rerender, waitFor } = renderHook(
       () =>
         useTables({
           dbId: expectDbId,
           schema: expectedSchema,
         }),
       {
-        wrapper: QueryProvider,
+        wrapper: createWrapper({
+          useRedux: true,
+        }),
       },
     );
-    await act(async () => {
-      jest.runAllTimers();
-    });
-    expect(fetchMock.calls(tableApiRoute).length).toBe(1);
+    await waitFor(() => expect(fetchMock.calls(tableApiRoute).length).toBe(1));
     rerender();
+    await waitFor(() => expect(result.current.data).toEqual(expectedData));
     expect(fetchMock.calls(tableApiRoute).length).toBe(1);
-    expect(result.current.data).toEqual(expectedData);
   });
 
   test('returns refreshed data after expires', async () => {
     const expectDbId = 'db1';
     const expectedSchema = 'schema1';
     const tableApiRoute = `glob:*/api/v1/database/${expectDbId}/tables/?q=*`;
-    fetchMock.get(tableApiRoute, fakeApiResult);
+    fetchMock.get(tableApiRoute, url =>
+      url.includes(expectedSchema) ? fakeApiResult : fakeHasMoreApiResult,
+    );
     fetchMock.get(`glob:*/api/v1/database/${expectDbId}/schemas/*`, {
       result: fakeSchemaApiResult,
     });
-    const { result, rerender } = renderHook(
-      () =>
+    const { result, rerender, waitFor } = renderHook(
+      ({ schema }) =>
         useTables({
           dbId: expectDbId,
-          schema: expectedSchema,
+          schema,
         }),
       {
-        wrapper: QueryProvider,
+        initialProps: { schema: expectedSchema },
+        wrapper: createWrapper({
+          useRedux: true,
+        }),
       },
     );
-    await act(async () => {
-      jest.runAllTimers();
-    });
-    expect(fetchMock.calls(tableApiRoute).length).toBe(1);
-    rerender();
-    await act(async () => {
-      jest.runAllTimers();
-    });
+
+    await waitFor(() => expect(result.current.data).toEqual(expectedData));
     expect(fetchMock.calls(tableApiRoute).length).toBe(1);
-    queryClient.clear();
-    rerender();
-    await act(async () => {
-      jest.runAllTimers();
-    });
+
+    rerender({ schema: 'schema2' });
+    await waitFor(() =>
+      expect(result.current.data).toEqual(expectedHasMoreData),
+    );
     expect(fetchMock.calls(tableApiRoute).length).toBe(2);
-    expect(result.current.data).toEqual(expectedData);
+
+    rerender({ schema: expectedSchema });
+    await waitFor(() => expect(result.current.data).toEqual(expectedData));
+    expect(fetchMock.calls(tableApiRoute).length).toBe(2);
+
+    // clean up cache
+    act(() => {

Review Comment:
   Same here. In most cases act is not needed. In fact, every render is [already encapsulated with act](https://davidwcai.medium.com/react-testing-library-and-the-not-wrapped-in-act-errors-491a5629193b).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] michael-s-molina commented on a diff in pull request #23760: chore(sqllab): Refactor react-query by redux-toolkit query

Posted by "michael-s-molina (via GitHub)" <gi...@apache.org>.
michael-s-molina commented on code in PR #23760:
URL: https://github.com/apache/superset/pull/23760#discussion_r1180300322


##########
superset-frontend/src/hooks/apiResources/schemas.ts:
##########
@@ -16,65 +16,97 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-import { useRef } from 'react';
-import { useQuery, UseQueryOptions } from 'react-query';
-import rison from 'rison';
-import { SupersetClient } from '@superset-ui/core';
-
-export type FetchSchemasQueryParams = {
-  dbId?: string | number;
-  forceRefresh?: boolean;
-};
-
-type QueryData = {
-  json: { result: string[] };
-  response: Response;
-};
+import { useCallback, useEffect, useRef } from 'react';
+import { api, JsonResponse } from './queryApi';
 
 export type SchemaOption = {
   value: string;
   label: string;
   title: string;
 };
 
-export function fetchSchemas({ dbId, forceRefresh }: FetchSchemasQueryParams) {
-  const queryParams = rison.encode({ force: forceRefresh });
-  // TODO: Would be nice to add pagination in a follow-up. Needs endpoint changes.
-  const endpoint = `/api/v1/database/${dbId}/schemas/?q=${queryParams}`;
-  return SupersetClient.get({ endpoint }) as Promise<QueryData>;
-}
+export type FetchSchemasQueryParams = {
+  dbId?: string | number;
+  forceRefresh: boolean;
+  onSuccess?: (data: SchemaOption[], isRefetched: boolean) => void;
+  onError?: () => void;
+};
+
+type Params = Omit<FetchSchemasQueryParams, 'forceRefresh'>;
+
+const schemaApi = api.injectEndpoints({
+  endpoints: builder => ({
+    schemas: builder.query<SchemaOption[], FetchSchemasQueryParams>({
+      providesTags: [{ type: 'Schemas', id: 'LIST' }],
+      query: ({ dbId, forceRefresh }) => ({
+        endpoint: `/api/v1/database/${dbId}/schemas/`,
+        // TODO: Would be nice to add pagination in a follow-up. Needs endpoint changes.
+        urlParams: {
+          force: forceRefresh,
+        },
+        transformResponse: ({ json }: JsonResponse) =>
+          json.result.map((value: string) => ({
+            value,
+            label: value,
+            title: value,
+          })),
+      }),
+      serializeQueryArgs: ({ queryArgs: { dbId } }) => ({
+        dbId,
+      }),
+    }),
+  }),
+});
 
-type Params = FetchSchemasQueryParams &
-  Pick<UseQueryOptions<SchemaOption[]>, 'onSuccess' | 'onError'>;
+export const { useLazySchemasQuery, useSchemasQuery } = schemaApi;
+
+const EMPTY_SCHEMAS = [] as SchemaOption[];
 
 export function useSchemas(options: Params) {
+  const isMountedRef = useRef(false);
   const { dbId, onSuccess, onError } = options || {};
-  const forceRefreshRef = useRef(false);
-  const params = { dbId };
-  const result = useQuery<QueryData, Error, SchemaOption[]>(
-    ['schemas', { dbId }],
-    () => fetchSchemas({ ...params, forceRefresh: forceRefreshRef.current }),
+  const [trigger, refetchResult] = useLazySchemasQuery();
+  const result = useSchemasQuery(
+    { dbId, forceRefresh: false },
     {
-      select: ({ json }) =>
-        json.result.map((value: string) => ({
-          value,
-          label: value,
-          title: value,
-        })),
-      enabled: Boolean(dbId),
-      onSuccess,
-      onError,
-      onSettled: () => {
-        forceRefreshRef.current = false;
-      },
+      skip: !dbId,
     },
   );
 
+  const refetch = useCallback(() => {
+    if (dbId) {
+      trigger({ dbId, forceRefresh: true }).then(
+        ({ isSuccess, isError, data }) => {
+          if (isSuccess) {
+            onSuccess?.(data || EMPTY_SCHEMAS, true);
+          }
+          if (isError) {
+            onError?.();
+          }
+        },
+      );
+    }
+  }, [dbId]);
+
+  useEffect(() => {
+    if (isMountedRef.current) {
+      const { requestId, isSuccess, isError, isFetching, data, originalArgs } =
+        result;
+      if (!originalArgs?.forceRefresh && requestId && !isFetching) {
+        if (isSuccess) {
+          onSuccess?.(data || EMPTY_SCHEMAS, false);
+        }
+        if (isError) {
+          onError?.();
+        }
+      }
+    } else {
+      isMountedRef.current = true;
+    }
+  }, [result]);

Review Comment:
   Can you resolve the dependency warnings of the effects?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] justinpark commented on a diff in pull request #23760: chore(sqllab): Refactor react-query by redux-toolkit query

Posted by "justinpark (via GitHub)" <gi...@apache.org>.
justinpark commented on code in PR #23760:
URL: https://github.com/apache/superset/pull/23760#discussion_r1173986199


##########
superset-frontend/spec/helpers/testing-library.tsx:
##########
@@ -81,8 +95,8 @@ export function createWrapper(options?: Options) {
       result = <BrowserRouter>{result}</BrowserRouter>;
     }
 
-    if (useQuery) {
-      result = <QueryProvider>{result}</QueryProvider>;
+    if (useQuery && !useRedux) {

Review Comment:
   oh it's not `useQueryParams`. (it's still [there](https://github.com/apache/superset/pull/23760/files/9dda4c6f14b8c8fe02b52bb445fe30fa376a833c#diff-003094fe62e8b418be60870591fb179b47fae671e2376a784c62ac4148b6c0eaL76)) the name looks confuse. I'll replace the name with `useApi` then.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] justinpark commented on a diff in pull request #23760: chore(sqllab): Refactor react-query by redux-toolkit query

Posted by "justinpark (via GitHub)" <gi...@apache.org>.
justinpark commented on code in PR #23760:
URL: https://github.com/apache/superset/pull/23760#discussion_r1177157232


##########
superset-frontend/spec/helpers/testing-library.tsx:
##########
@@ -81,8 +95,8 @@ export function createWrapper(options?: Options) {
       result = <BrowserRouter>{result}</BrowserRouter>;
     }
 
-    if (useQuery) {
-      result = <QueryProvider>{result}</QueryProvider>;
+    if (useApi && !useRedux) {

Review Comment:
   @michael-s-molina sounds good. I updated with `useRedux`
   (yeah it looks like no longer needed since this option for react-query wrapper)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] michael-s-molina commented on a diff in pull request #23760: chore(sqllab): Refactor react-query by redux-toolkit query

Posted by "michael-s-molina (via GitHub)" <gi...@apache.org>.
michael-s-molina commented on code in PR #23760:
URL: https://github.com/apache/superset/pull/23760#discussion_r1180293144


##########
superset-frontend/spec/helpers/testing-library.tsx:
##########
@@ -62,14 +70,20 @@ export function createWrapper(options?: Options) {
     }
 
     if (useRedux) {
-      const mockStore =
-        store ??
-        configureStore({
-          preloadedState: initialState || {},
+      let storeWithInitialState;
+      if (initialState || reducers) {
+        storeWithInitialState = configureStore({
+          preloadedState: initialState,
           devTools: false,
-          reducer: reducers || reducerIndex,
+          reducer: {
+            ...(reducers || reducerIndex),
+            [api.reducerPath]: api.reducer,
+          },
+          middleware: getDefaultMiddleware =>
+            getDefaultMiddleware().concat(api.middleware),
         });
-
+      }
+      const mockStore = store ?? storeWithInitialState ?? storeWithApi;

Review Comment:
   I think the logic here should consider the `store` parameter. There's no difference between `storeWithInitialState` and `storeWithApi` with the exception of the `initialState`. Both use the API and the reducers should be the same. I suggest something like:
   
   `const mockStore = store ?? configureStore({...,  preloadedState: initialState || {}}) `
   
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] michael-s-molina commented on a diff in pull request #23760: chore(sqllab): Refactor react-query by redux-toolkit query

Posted by "michael-s-molina (via GitHub)" <gi...@apache.org>.
michael-s-molina commented on code in PR #23760:
URL: https://github.com/apache/superset/pull/23760#discussion_r1184878848


##########
superset-frontend/spec/helpers/testing-library.tsx:
##########
@@ -65,11 +72,15 @@ export function createWrapper(options?: Options) {
       const mockStore =
         store ??
         configureStore({
-          preloadedState: initialState || {},
+          preloadedState: initialState,
           devTools: false,
-          reducer: reducers || reducerIndex,
+          reducer: {
+            ...(reducers || reducerIndex),
+            [api.reducerPath]: api.reducer,
+          },
+          middleware: getDefaultMiddleware =>
+            getDefaultMiddleware().concat(api.middleware),
         });

Review Comment:
   `const mockStore = store ?? createStore(initialState, reducers);`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


[GitHub] [superset] justinpark commented on pull request #23760: chore(sqllab): Refactor react-query by redux-toolkit query

Posted by "justinpark (via GitHub)" <gi...@apache.org>.
justinpark commented on PR #23760:
URL: https://github.com/apache/superset/pull/23760#issuecomment-1533860529

   @michael-s-molina I fixed all addressed issues. Please take a look


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org