You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by ly...@apache.org on 2023/01/19 16:36:08 UTC

[superset] 14/21: Fix useEffect warnings and autosetting db from local storage, add translations, change window.location.href redirect to use history.push()

This is an automated email from the ASF dual-hosted git repository.

lyndsi pushed a commit to branch lyndsi/enable-dataset-creation
in repository https://gitbox.apache.org/repos/asf/superset.git

commit 50bd46d2dfcd74576e5e5467d78ae04265f55243
Author: lyndsiWilliams <kc...@gmail.com>
AuthorDate: Thu Jan 12 13:28:53 2023 -0600

    Fix useEffect warnings and autosetting db from local storage, add translations, change window.location.href redirect to use history.push()
---
 .../CRUD/data/database/DatabaseModal/index.tsx     |  6 +-
 .../data/dataset/AddDataset/DatasetPanel/index.tsx | 10 ++-
 .../data/dataset/AddDataset/LeftPanel/index.tsx    | 98 +++++++++++++---------
 .../views/CRUD/data/dataset/AddDataset/index.tsx   | 25 +++---
 .../views/CRUD/data/dataset/AddDataset/types.tsx   |  8 +-
 superset-frontend/src/views/CRUD/data/hooks.ts     |  6 +-
 6 files changed, 89 insertions(+), 64 deletions(-)

diff --git a/superset-frontend/src/views/CRUD/data/database/DatabaseModal/index.tsx b/superset-frontend/src/views/CRUD/data/database/DatabaseModal/index.tsx
index c3500839d7..5f85ae0985 100644
--- a/superset-frontend/src/views/CRUD/data/database/DatabaseModal/index.tsx
+++ b/superset-frontend/src/views/CRUD/data/database/DatabaseModal/index.tsx
@@ -31,6 +31,7 @@ import React, {
   useReducer,
   Reducer,
 } from 'react';
+import { useHistory } from 'react-router-dom';
 import { setItem, LocalStorageKeys } from 'src/utils/localStorageHelpers';
 import { UploadChangeParam, UploadFile } from 'antd/lib/upload/interface';
 import Tabs from 'src/components/Tabs';
@@ -518,6 +519,7 @@ const DatabaseModal: FunctionComponent<DatabaseModalProps> = ({
     t('database'),
     addDangerToast,
   );
+  const history = useHistory();
 
   const [tabKey, setTabKey] = useState<string>(DEFAULT_TAB_KEY);
   const [availableDbs, getAvailableDbs] = useAvailableDatabases();
@@ -1295,7 +1297,7 @@ const DatabaseModal: FunctionComponent<DatabaseModalProps> = ({
         onClick={() => {
           setLoading(true);
           fetchAndSetDB();
-          window.location.href = '/dataset/add/';
+          history.push('/dataset/add/');
         }}
       >
         {t('CREATE DATASET')}
@@ -1306,7 +1308,7 @@ const DatabaseModal: FunctionComponent<DatabaseModalProps> = ({
         onClick={() => {
           setLoading(true);
           fetchAndSetDB();
-          window.location.href = `/superset/sqllab/?db=true`;
+          history.push(`/superset/sqllab/?db=true`);
         }}
       >
         {t('QUERY DATA IN SQL LAB')}
diff --git a/superset-frontend/src/views/CRUD/data/dataset/AddDataset/DatasetPanel/index.tsx b/superset-frontend/src/views/CRUD/data/dataset/AddDataset/DatasetPanel/index.tsx
index 56939258e1..1095f044a0 100644
--- a/superset-frontend/src/views/CRUD/data/dataset/AddDataset/DatasetPanel/index.tsx
+++ b/superset-frontend/src/views/CRUD/data/dataset/AddDataset/DatasetPanel/index.tsx
@@ -17,7 +17,7 @@
  * under the License.
  */
 import React, { useEffect, useState, useRef } from 'react';
-import { SupersetClient, logging } from '@superset-ui/core';
+import { SupersetClient, logging, t } from '@superset-ui/core';
 import { DatasetObject } from 'src/views/CRUD/data/dataset/AddDataset/types';
 import { addDangerToast } from 'src/components/MessageToasts/actions';
 import DatasetPanel from './DatasetPanel';
@@ -96,10 +96,14 @@ const DatasetPanelWrapper = ({
         setHasColumns?.(false);
         setHasError(true);
         addDangerToast(
-          `The API response from ${path} does not match the IDatabaseTable interface.`,
+          t(
+            'The API response from %s does not match the IDatabaseTable interface.',
+          ),
         );
         logging.error(
-          `The API response from ${path} does not match the IDatabaseTable interface.`,
+          t(
+            'The API response from %s does not match the IDatabaseTable interface.',
+          ),
         );
       }
     } catch (error) {
diff --git a/superset-frontend/src/views/CRUD/data/dataset/AddDataset/LeftPanel/index.tsx b/superset-frontend/src/views/CRUD/data/dataset/AddDataset/LeftPanel/index.tsx
index be9181c70a..14dd7dca4b 100644
--- a/superset-frontend/src/views/CRUD/data/dataset/AddDataset/LeftPanel/index.tsx
+++ b/superset-frontend/src/views/CRUD/data/dataset/AddDataset/LeftPanel/index.tsx
@@ -16,7 +16,13 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-import React, { useEffect, useState, SetStateAction, Dispatch } from 'react';
+import React, {
+  useEffect,
+  useState,
+  SetStateAction,
+  Dispatch,
+  useCallback,
+} from 'react';
 import {
   SupersetClient,
   t,
@@ -41,13 +47,15 @@ import {
 } from 'src/components/EmptyState';
 import { useToasts } from 'src/components/MessageToasts/withToasts';
 import { LocalStorageKeys, getItem } from 'src/utils/localStorageHelpers';
-import { DatasetActionType } from '../types';
+import {
+  DatasetActionType,
+  DatasetObject,
+} from 'src/views/CRUD/data/dataset/AddDataset/types';
 
 interface LeftPanelProps {
   setDataset: Dispatch<SetStateAction<object>>;
-  schema?: string | null | undefined;
-  dbId?: number;
-  datasets?: (string | null | undefined)[] | undefined;
+  dataset?: Partial<DatasetObject> | null;
+  datasetNames?: (string | null | undefined)[] | undefined;
 }
 
 const SearchIcon = styled(Icons.Search)`
@@ -146,9 +154,8 @@ const LeftPanelStyle = styled.div`
 
 export default function LeftPanel({
   setDataset,
-  schema,
-  dbId,
-  datasets,
+  dataset,
+  datasetNames,
 }: LeftPanelProps) {
   const theme = useTheme();
 
@@ -161,11 +168,14 @@ export default function LeftPanel({
 
   const { addDangerToast } = useToasts();
 
-  const setDatabase = (db: Partial<DatabaseObject>) => {
-    setDataset({ type: DatasetActionType.selectDatabase, payload: { db } });
-    setSelectedTable(null);
-    setResetTables(true);
-  };
+  const setDatabase = useCallback(
+    (db: Partial<DatabaseObject>) => {
+      setDataset({ type: DatasetActionType.selectDatabase, payload: { db } });
+      setSelectedTable(null);
+      setResetTables(true);
+    },
+    [setDataset],
+  );
 
   const setTable = (tableName: string, index: number) => {
     setSelectedTable(index);
@@ -175,29 +185,32 @@ export default function LeftPanel({
     });
   };
 
-  const getTablesList = (url: string) => {
-    SupersetClient.get({ url })
-      .then(({ json }) => {
-        const options: TableOption[] = json.options.map((table: Table) => {
-          const option: TableOption = {
-            value: table.value,
-            label: <TableOption table={table} />,
-            text: table.label,
-          };
+  const getTablesList = useCallback(
+    (url: string) => {
+      SupersetClient.get({ url })
+        .then(({ json }) => {
+          const options: TableOption[] = json.options.map((table: Table) => {
+            const option: TableOption = {
+              value: table.value,
+              label: <TableOption table={table} />,
+              text: table.label,
+            };
 
-          return option;
-        });
+            return option;
+          });
 
-        setTableOptions(options);
-        setLoadTables(false);
-        setResetTables(false);
-        setRefresh(false);
-      })
-      .catch(error => {
-        addDangerToast('There was an error fetching tables');
-        logging.error('There was an error fetching tables', error);
-      });
-  };
+          setTableOptions(options);
+          setLoadTables(false);
+          setResetTables(false);
+          setRefresh(false);
+        })
+        .catch(error => {
+          addDangerToast(t('There was an error fetching tables'));
+          logging.error(t('There was an error fetching tables'), error);
+        });
+    },
+    [addDangerToast],
+  );
 
   const setSchema = (schema: string) => {
     if (schema) {
@@ -211,7 +224,9 @@ export default function LeftPanel({
     setResetTables(true);
   };
 
-  const encodedSchema = schema ? encodeURIComponent(schema) : undefined;
+  const encodedSchema = dataset?.schema
+    ? encodeURIComponent(dataset?.schema)
+    : undefined;
 
   useEffect(() => {
     const currentUserSelectedDb = getItem(
@@ -221,16 +236,16 @@ export default function LeftPanel({
     if (currentUserSelectedDb) {
       setDatabase(currentUserSelectedDb);
     }
-  }, []);
+  }, [setDatabase]);
 
   useEffect(() => {
     if (loadTables) {
       const endpoint = encodeURI(
-        `/superset/tables/${dbId}/${encodedSchema}/${refresh}/`,
+        `/superset/tables/${dataset?.db?.id}/${encodedSchema}/${refresh}/`,
       );
       getTablesList(endpoint);
     }
-  }, [loadTables]);
+  }, [loadTables, dataset?.db?.id, encodedSchema, getTablesList, refresh]);
 
   useEffect(() => {
     if (resetTables) {
@@ -274,6 +289,7 @@ export default function LeftPanel({
         {SELECT_DATABASE_AND_SCHEMA_TEXT}
       </p>
       <DatabaseSelector
+        db={dataset?.db}
         handleError={addDangerToast}
         onDbChange={setDatabase}
         onSchemaChange={setSchema}
@@ -281,7 +297,7 @@ export default function LeftPanel({
         onEmptyResults={onEmptyResults}
       />
       {loadTables && !refresh && Loader(TABLE_LOADING_TEXT)}
-      {schema && !loadTables && !tableOptions.length && !searchVal && (
+      {dataset?.schema && !loadTables && !tableOptions.length && !searchVal && (
         <div className="emptystate">
           <EmptyStateMedium
             image="empty-table.svg"
@@ -291,7 +307,7 @@ export default function LeftPanel({
         </div>
       )}
 
-      {schema && (tableOptions.length > 0 || searchVal.length > 0) && (
+      {dataset?.schema && (tableOptions.length > 0 || searchVal.length > 0) && (
         <>
           <Form>
             <p className="table-title">{SELECT_DATABASE_TABLE_TEXT}</p>
@@ -335,7 +351,7 @@ export default function LeftPanel({
                   onClick={() => setTable(option.value, i)}
                 >
                   {option.label}
-                  {datasets?.includes(option.value) && (
+                  {datasetNames?.includes(option.value) && (
                     <Icons.Warning
                       iconColor={
                         selectedTable === i
diff --git a/superset-frontend/src/views/CRUD/data/dataset/AddDataset/index.tsx b/superset-frontend/src/views/CRUD/data/dataset/AddDataset/index.tsx
index 005e654627..05ffc3a343 100644
--- a/superset-frontend/src/views/CRUD/data/dataset/AddDataset/index.tsx
+++ b/superset-frontend/src/views/CRUD/data/dataset/AddDataset/index.tsx
@@ -16,8 +16,14 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-import React, { useReducer, Reducer, useEffect, useState } from 'react';
-import { logging } from '@superset-ui/core';
+import React, {
+  useReducer,
+  Reducer,
+  useEffect,
+  useState,
+  useCallback,
+} from 'react';
+import { logging, t } from '@superset-ui/core';
 import { UseGetDatasetsList } from 'src/views/CRUD/data/hooks';
 import rison from 'rison';
 import { addDangerToast } from 'src/components/MessageToasts/actions';
@@ -92,22 +98,22 @@ export default function AddDataset() {
       })
     : undefined;
 
-  const getDatasetsList = async () => {
+  const getDatasetsList = useCallback(async () => {
     await UseGetDatasetsList(queryParams)
       .then(json => {
         setDatasets(json?.result);
       })
       .catch(error => {
-        addDangerToast('There was an error fetching dataset');
-        logging.error('There was an error fetching dataset', error);
+        addDangerToast(t('There was an error fetching dataset'));
+        logging.error(t('There was an error fetching dataset'), error);
       });
-  };
+  }, [queryParams]);
 
   useEffect(() => {
     if (dataset?.schema) {
       getDatasetsList();
     }
-  }, [dataset?.schema]);
+  }, [dataset?.schema, getDatasetsList]);
 
   const HeaderComponent = () => (
     <Header setDataset={setDataset} title={dataset?.table_name} />
@@ -116,9 +122,8 @@ export default function AddDataset() {
   const LeftPanelComponent = () => (
     <LeftPanel
       setDataset={setDataset}
-      schema={dataset?.schema}
-      dbId={dataset?.db?.id}
-      datasets={datasetNames}
+      dataset={dataset}
+      datasetNames={datasetNames}
     />
   );
 
diff --git a/superset-frontend/src/views/CRUD/data/dataset/AddDataset/types.tsx b/superset-frontend/src/views/CRUD/data/dataset/AddDataset/types.tsx
index dbeef93ead..9fc1bf3e70 100644
--- a/superset-frontend/src/views/CRUD/data/dataset/AddDataset/types.tsx
+++ b/superset-frontend/src/views/CRUD/data/dataset/AddDataset/types.tsx
@@ -16,6 +16,8 @@
  * specific language governing permissions and limitations
  * under the License.
  */
+import { DatabaseObject } from 'src/components/DatabaseSelector';
+
 export enum DatasetActionType {
   selectDatabase,
   selectSchema,
@@ -24,11 +26,7 @@ export enum DatasetActionType {
 }
 
 export interface DatasetObject {
-  db: {
-    id: number;
-    database_name?: string;
-    owners?: number[];
-  };
+  db: DatabaseObject;
   schema?: string | null;
   dataset_name: string;
   table_name?: string | null;
diff --git a/superset-frontend/src/views/CRUD/data/hooks.ts b/superset-frontend/src/views/CRUD/data/hooks.ts
index 82c63bb320..e15e4be957 100644
--- a/superset-frontend/src/views/CRUD/data/hooks.ts
+++ b/superset-frontend/src/views/CRUD/data/hooks.ts
@@ -17,7 +17,7 @@
  * under the License.
  */
 import { useState, useEffect } from 'react';
-import { SupersetClient, logging } from '@superset-ui/core';
+import { SupersetClient, logging, t } from '@superset-ui/core';
 import { addDangerToast } from 'src/components/MessageToasts/actions';
 
 type BaseQueryObject = {
@@ -82,6 +82,6 @@ export const UseGetDatasetsList = (queryParams: string | undefined) =>
   })
     .then(({ json }) => json)
     .catch(error => {
-      addDangerToast('There was an error fetching dataset');
-      logging.error('There was an error fetching dataset', error);
+      addDangerToast(t('There was an error fetching dataset'));
+      logging.error(t('There was an error fetching dataset'), error);
     });