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

DataStore.clear() Error : [TypeError: undefined is not a function] #10764

Closed
3 tasks done
santhoshpriya0715 opened this issue Dec 12, 2022 · 23 comments
Closed
3 tasks done
Assignees
Labels
bug Something isn't working DataStore Related to DataStore category

Comments

@santhoshpriya0715
Copy link

Before opening, please confirm:

JavaScript Framework

React Native

Amplify APIs

DataStore

Amplify Categories

Not applicable

Environment information

# Put output below this line

  System:
    OS: Windows 10 10.0.22000
    CPU: (12) x64 11th Gen Intel(R) Core(TM) i5-11400F @ 2.60GHz
    Memory: 3.14 GB / 15.84 GB
  Binaries:
    Node: 16.13.0 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.18 - C:\Program Files\nodejs\yarn.CMD
    npm: 8.18.0 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Edge: Spartan (44.22000.120.0), Chromium (108.0.1462.46)
    Internet Explorer: 11.0.22000.120
  npmPackages:
    @alessiocancian/react-native-actionsheet: ^3.2.0 => 3.2.0 
    @aws-amplify/datastore-storage-adapter: ^2.0.5 => 2.0.5 
    @aws-amplify/pushnotification: ^5.0.5 => 5.0.5 
    @aws-sdk/client-codeguruprofiler: ^3.226.0 => 3.226.0 
    @aws-sdk/client-xray: ^3.226.0 => 3.226.0 
    @azure/core-asynciterator-polyfill: ^1.0.2 => 1.0.2 
    @babel/core: ^7.20.5 => 7.20.5 
    @babel/runtime: ^7.20.6 => 7.20.6 
    @react-native-async-storage/async-storage: ^1.17.11 => 1.17.11 
    @react-native-community/eslint-config: ^3.2.0 => 3.2.0 
    @react-native-community/netinfo: ^9.3.7 => 9.3.7 
    @react-native-community/push-notification-ios: ^1.10.1 => 1.10.1 (1.0.3)
    @react-navigation/bottom-tabs: ^6.5.0 => 6.5.0 
    @react-navigation/native: ^6.1.0 => 6.1.0 
    @react-navigation/native-stack: ^6.9.5 => 6.9.5 
    @react-navigation/stack: ^6.3.8 => 6.3.8 
    @reduxjs/toolkit: ^1.9.1 => 1.9.1 
    @reduxjs/toolkit-query:  1.0.0 
    @reduxjs/toolkit-query-react:  1.0.0 
    @tsconfig/react-native: ^2.0.3 => 2.0.3 
    @types/jest: ^29.2.4 => 29.2.4 
    @types/react: ^18.0.26 => 18.0.26 
    @types/react-native: ^0.70.8 => 0.70.8 
    @types/react-test-renderer: ^18.0.0 => 18.0.0 
    HelloWorld:  0.0.1 
    amazon-cognito-identity-js: ^6.0.1 => 6.0.1 (5.2.12)
    amplify: ^0.0.11 => 0.0.11 
    aws-amplify: ^5.0.5 => 5.0.5 
    babel-jest: ^29.3.1 => 29.3.1 
    crypto-js: ^4.1.1 => 4.1.1 (3.3.0)
    eslint: ^8.29.0 => 8.29.0 
    hermes-inspector-msggen:  1.0.0 
    jest: ^29.3.1 => 29.3.1 
    metro-react-native-babel-preset: ^0.73.4 => 0.73.4 (0.67.0)
    moment: ^2.29.4 => 2.29.4 
    react: ^17.0.2 => 17.0.2 
    react-native: 0.68.2 => 0.68.2 
    react-native-blob-util: ^0.17.0 => 0.17.0 
    react-native-chart-kit: ^6.12.0 => 6.12.0 
    react-native-curved-bottom-bar: ^2.1.4 => 2.1.4 
    react-native-date-picker: ^4.2.6 => 4.2.6 
    react-native-element-dropdown: ^2.5.0 => 2.5.0 
    react-native-gesture-handler: ^2.8.0 => 2.8.0 
    react-native-get-random-values: ^1.8.0 => 1.8.0 
    react-native-image-picker: ^4.10.2 => 4.10.2 
    react-native-image-zoom-viewer: ^3.0.1 => 3.0.1 
    react-native-linear-gradient: ^2.6.2 => 2.6.2 
    react-native-modal: ^13.0.1 => 13.0.1 
    react-native-pager-view: ^6.1.2 => 6.1.2 
    react-native-pdf: ^6.6.2 => 6.6.2 
    react-native-reanimated: ^2.13.0 => 2.13.0 
    react-native-safe-area-context: ^4.4.1 => 4.4.1 
    react-native-scoped-storage: ^1.9.3 => 1.9.3 
    react-native-screens: ^3.18.2 => 3.18.2 
    react-native-splash-screen: ^3.3.0 => 3.3.0 
    react-native-sqlite-storage: ^6.0.1 => 6.0.1 
    react-native-svg: ^13.6.0 => 13.6.0 
    react-native-switch-selector: ^2.3.0 => 2.3.0 
    react-native-touch-id: ^4.4.1 => 4.4.1 
    react-native-url-polyfill: ^1.3.0 => 1.3.0 
    react-native-uuid: ^2.0.1 => 2.0.1 
    react-native-vision-camera: ^2.15.2 => 2.15.2 
    react-native-webview: ^11.26.0 => 11.26.0 
    react-redux: ^8.0.5 => 8.0.5 
    react-test-renderer: 17.0.2 => 17.0.2 
    redux: ^4.2.0 => 4.2.0 
    redux-persist: ^6.0.0 => 6.0.0 
    redux-persist/integration/react:  undefined ()
    redux-thunk: ^2.4.2 => 2.4.2 
    typescript: ^4.9.4 => 4.9.4 
  npmGlobalPackages:
    @aws-amplify/cli: 9.1.0
    @react-native-community/cli-platform-android: 7.0.1
    eas-cli: 0.48.2
    expo-cli: 5.2.0
    npm: 8.18.0
    react-native-cli: 2.0.1
    react-native-paper: 4.12.0
    react-native-webview: 11.17.2
    yarn: 1.22.18

Describe the bug

I am using "aws-amplify": "^4.3.43" , "@aws-amplify/cli": "^9.1.0",
[TypeError: undefined is not a function] When Calling Datastore.clear() function

Expected behavior

Expected to clear local data, But it doesn't seams to clear

Reproduction steps

DataStore.clear();

Code Snippet

// Put your code below this line.

const onSignOut = async () => {
try {

  await DataStore.clear()
  await Auth.signOut().catch(error => {
    Alert.alert(error.message);
  });
} catch (error) {
  console.log('log Datastore: ', error)
}

};

Log output

// Put your logs below this line


aws-exports.js

No response

Manual configuration

No response

Additional configuration

No response

Mobile Device

No response

Mobile Operating System

No response

Mobile Browser

No response

Mobile Browser Version

No response

Additional information and screenshots

No response

@santhoshpriya0715 santhoshpriya0715 changed the title DataStore Error : [TypeError: undefined is not a function] DataStore.clear() Error : [TypeError: undefined is not a function] Dec 12, 2022
@tannerabread tannerabread added DataStore Related to DataStore category pending-triage Issue is pending triage labels Dec 12, 2022
@chrisbonifacio
Copy link
Member

Hi @santhoshpriya0715 👋 thanks for raising this issue! While I try to reproduce the error, can you try deleting your node_modules folder, upgrading to the latest version of aws-amplify, and re-installing your dependencies?

Let me know if the issue persists afterwards.

@chrisbonifacio chrisbonifacio self-assigned this Dec 12, 2022
@chrisbonifacio chrisbonifacio added pending-response to-be-reproduced Used in order for Amplify to reproduce said issue and removed pending-triage Issue is pending triage labels Dec 12, 2022
@jeromeheissler
Copy link

Same problem with version 5.0.5 of aws-amplify.

I've tried to stop datastore before clear with that code :

const logger = new Logger('App');
export default function App() {
  const [loading, setLoading] = useState(false);
  useEffect(() => {
    setLoading(true);
    logger.info('stop');
    DataStore.stop()
      .then(() => {
        logger.info('clear');
        return DataStore.clear();
      })
      .then(() => {
        logger.info('start');
        return DataStore.start();
      })
      .then(() => {
        logger.info('started');
        setLoading(false);
      })
      .catch(err => {
        logger.error('unbable to clear DataStore', err);
      });
  }, []);

  return loading ? (
    <View />
  ) : (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
          <NavigationContainer>
            <Route />
          </NavigationContainer>
      </PersistGate>
    </Provider>
  );
}

In the log i can see :

 BUNDLE  ./index.js 

 LOG  Running "myapp" with {"rootTag":51,"initialProps":{}}
 LOG  [INFO] 09:10.750 App - stop
 ERROR  [ERROR] 09:10.805 App - unbable to clear DataStore [TypeError: undefined is not a function]

@santhoshpriya0715
Copy link
Author

santhoshpriya0715 commented Dec 14, 2022 via email

@santhoshpriya0715
Copy link
Author

santhoshpriya0715 commented Dec 14, 2022 via email

@santhoshpriya0715
Copy link
Author

Hi @santhoshpriya0715 👋 thanks for raising this issue! While I try to reproduce the error, can you try deleting your node_modules folder, upgrading to the latest version of aws-amplify, and re-installing your dependencies?

Let me know if the issue persists afterwards.

Yes, I tried what you say but its not working.

@imdkbj
Copy link

imdkbj commented Dec 15, 2022

Facing the same.

"aws-amplify": "^5.0.5",

amplify -v
10.5.2
import React from 'react';
import { Provider } from 'react-redux';
import Toast from 'react-native-toast-notifications';
import { PersistGate } from 'redux-persist/integration/react';
import { Amplify, AuthModeStrategyType, DataStore, Hub } from 'aws-amplify';
import { SQLiteAdapter } from '@aws-amplify/datastore-storage-adapter/SQLiteAdapter';

import { store, persistor } from './redux/store';

import './translation';
import './utils/notification';
import './utils/interceptors';

import { handleLogout } from './utils/logout';

import awsconfig from './aws-exports';

import App from './App';

Amplify.configure({
    ...awsconfig,
    DataStore: {
        authModeStrategyType: AuthModeStrategyType.MULTI_AUTH,
    },
});

// Amplify.Logger.LOG_LEVEL = 'DEBUG';

DataStore.configure({
    storageAdapter: SQLiteAdapter,
    errorHandler: error => {
        console.warn('DataStore error', error);
    },
});

Hub.listen('auth', async data => {
    switch (data.payload.event) {
        case 'signOut':
            try {
                await handleLogout();
                await DataStore?.stop?.();
                await DataStore?.clear?.();
            } catch (error) {
                console.log('Hub signOut error', error);
            }
            break;
        default:
            break;
    }
});

const ClientApp = () => {
    return (
        <Provider store={store}>
            <PersistGate loading={null} persistor={persistor}>
                <App />
                <Toast ref={ref => (global.toast = ref)} />
            </PersistGate>
        </Provider>
    );
};

export default ClientApp;
import { Dimensions, Platform } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

import { actions as authActions, deleteFCMToken } from '../redux/auth';
import { actions as projectActions } from '../redux/project';
import { actions as homeActions } from '../redux/home';
import { store } from '../redux/store';
import { startWatch } from './location';

const { width, height } = Dimensions.get('screen');

export const handleLogout = async () => {
    try {
        const data = {
            platform: Platform.OS,
            version: Platform.Version,
            width,
            height,
        };
        startWatch('unsubscribe');
        await store.dispatch(deleteFCMToken(data));
        store.dispatch(authActions.setLogOut());
        store.dispatch(homeActions.resetData());
        store.dispatch(projectActions.resetData());
        await AsyncStorage.setItem('TENANT', '0');
    } catch (error) {
        console.log('handleLogout Error', error);
    }
};
 LOG  Hub signOut error [TypeError: undefined is not a function]

@chrisbonifacio
Copy link
Member

@jeromeheissler and @imdkbj I noticed you are both calling DataStop.stop before DataStore.clear. Can you try just calling DataStore.clear? and let me know if the issue persists?

@imdkbj
Copy link

imdkbj commented Dec 16, 2022

Same thing.

 LOG  Hub signOut error [TypeError: undefined is not a function]
    try {
                await handleLogout();
                // await DataStore?.stop?.();
                await DataStore?.clear?.();
            } catch (error) {
                console.log('Hub signOut error', error);
            }

@santhoshpriya0715
Copy link
Author

santhoshpriya0715 commented Dec 16, 2022

@jeromeheissler and @imdkbj I noticed you are both calling DataStop.stop before DataStore.clear. Can you try just calling DataStore.clear? and let me know if the issue persists?

Yes, Its, continued, not working

@santhoshpriya0715
Copy link
Author

We have a temporary solution for Datastore clear and Datastore stop,
use "aws-amplify": "4.3.37", this version handle datastore clear and datastore stop.

But why we can't use "aws-amplify"@latest

@chrisbonifacio
Copy link
Member

@santhoshpriya0715 and @jeromeheissler can either of you confirm that you're using the SQLite adapter, similar to @imdkbj ?

@santhoshpriya0715
Copy link
Author

@santhoshpriya0715 and @jeromeheissler can either of you confirm that you're using the SQLite adapter, similar to @imdkbj ?

yes, exactly what @imdkbj used.

@jeromeheissler
Copy link

@santhoshpriya0715 and @jeromeheissler can either of you confirm that you're using the SQLite adapter, similar to @imdkbj ?

I'm not using it.

@chrisbonifacio chrisbonifacio added bug Something isn't working and removed to-be-reproduced Used in order for Amplify to reproduce said issue labels Dec 20, 2022
@dpilch
Copy link
Member

dpilch commented Dec 20, 2022

Work Around (TLDR)

Add the polyfill to your dependencies.

npm install --save promise.allsettled

Then add the following to somewhere near the root of your app (such as index.js).

import allSettled from 'promise.allsettled';

allSettled.shim();

Explanation

The issue is that the polyfill for Promise used by Hermes does not include Promise.allSettled (or Promise.any). react-native@0.70.6 added support for Promise.allSettled (and Promise.any). However, React Native will use the Promise polyfill from Hermes if it is available (according to facebook/react-native#35363 (comment)) resulting in Promise.allSettled still missing when using Hermes. This will be fixed in react-native@0.71.x (facebook/hermes#766 (comment)).

The workaround suggested in facebook/hermes#766 (comment) will unblock current versions of React Native.

The workaround is clearly not a great experience, so we will be looking into a proper fix.

@santhoshpriya0715
Copy link
Author

Work Around (TLDR)

Add the polyfill to your dependencies.

npm install --save promise.allsettled

Then add the following to somewhere near the root of your app (such as index.js).

import allSettled from 'promise.allsettled';

allSettled.shim();

Explanation

The issue is that the polyfill for Promise used by Hermes does not include Promise.allSettled (or Promise.any). react-native@0.70.6 added support for Promise.allSettled (and Promise.any). However, React Native will use the Promise polyfill from Hermes if it is available (according to facebook/react-native#35363 (comment)) resulting in Promise.allSettled still missing when using Hermes. This will be fixed in react-native@0.71.x (facebook/hermes#766 (comment)).

The workaround suggested in facebook/hermes#766 (comment) will unblock current versions of React Native.

The workaround is clearly not a great experience, so we will be looking into a proper fix.

As you said we tried allSettled.shim(), Datastore.clear() and Datastore.stop() in aws-amplify@4.3.42 worked.
But, we tried this in aws-amplfy@5.0.7(latest), we have issue in Datastore.start() itself, it shows error something like this "object is not undefined".

Though it worked in aws-amplify@4.3.42, it has relationship link issue once datastore is cleared & stopped and started again.
WARN Possible Unhandled Promise Rejection (id: 0):
Object {
"code": 0,
"message": "duplicate column name: undefined (code 1 SQLITE_ERROR): , while compiling: CREATE TABLE IF NOT EXISTS "Receipt" ("id" PRIMARY KEY NOT NULL, "type" INTEGER NOT NULL, "payerMerchant" TEXT, "date" TEXT, "totalAmount" REAL, "subTotal" REAL, "tax" REAL, "otherTax" REAL, "categoryID" TEXT NOT NULL, "accountID" TEXT NOT NULL, "category" TEXT, "undefined" TEXT, "account" TEXT, "undefined" TEXT, "forBusiness" INTEGER, "addNotes" TEXT, "verified" INTEGER, "approved" INTEGER, "extractCompleted" INTEGER, "receiptImage" TEXT, "userId" TEXT NOT NULL, "cpaNotes" TEXT, "createdDate" TEXT NOT NULL, "isDeleted" INTEGER, "createdAt" TEXT, "updatedAt" TEXT, "_version" INTEGER, "_lastChangedAt" INTEGER, "_deleted" INTEGER);",
}
WARN Possible Unhandled Promise Rejection (id: 1):
Object {
"code": 0,
"message": "no such table: Setting (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM "Setting" WHERE ("key" = ?) ORDER BY rowid ASC LIMIT ?",
}

However, when we force close app and open app with new datastore configure, it works.

@dpilch
Copy link
Member

dpilch commented Dec 22, 2022

Looks like Hermes is also missing Symbol.asyncIterator. facebook/hermes#820

The polyfill from core-js should solve this.

npm install --save core-js

Then add this as the top of the imports for your app.

import 'core-js/full/symbol/async-iterator';

@santhoshpriya0715
Copy link
Author

Symbol.asyncIterator issue cleared, But below issue not solved yet.
At Datastore.Clear() resync datastore

WARN Possible Unhandled Promise Rejection (id: 0):

Object {
"code": 0,
"message": "duplicate column name: undefined (code 1 SQLITE_ERROR): , while compiling: CREATE TABLE IF NOT EXISTS "Receipt" ("id" PRIMARY KEY NOT NULL, "type" INTEGER NOT NULL, "payerMerchant" TEXT, "date" TEXT, "totalAmount" REAL, "subTotal" REAL, "tax" REAL, "otherTax" REAL, "categoryID" TEXT NOT NULL, "accountID" TEXT NOT NULL, "category" TEXT, "undefined" TEXT, "account" TEXT, "undefined" TEXT, "forBusiness" INTEGER, "addNotes" TEXT, "verified" INTEGER, "approved" INTEGER, "extractCompleted" INTEGER, "receiptImage" TEXT, "userId" TEXT NOT NULL, "cpaNotes" TEXT, "createdDate" TEXT NOT NULL, "isDeleted" INTEGER, "createdAt" TEXT, "updatedAt" TEXT, "_version" INTEGER, "_lastChangedAt" INTEGER, "_deleted" INTEGER);",
}
WARN Possible Unhandled Promise Rejection (id: 1):
Object {
"code": 0,
"message": "no such table: Setting (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM "Setting" WHERE ("key" = ?) ORDER BY rowid ASC LIMIT ?",
} ###

@dpilch
Copy link
Member

dpilch commented Dec 27, 2022

@santhoshpriya0715, I am unable to reproduce this error. Can you open a new issue with the minimum reproduction?

@ervibern
Copy link

ervibern commented Jan 3, 2023

I was having the same error when using this import
import { DataStore } from 'aws-amplify';
but then switched to this and the error disappeared
import { DataStore } from '@aws-amplify/datastore';

@chrisbonifacio
Copy link
Member

Hi @santhoshpriya0715 👋 can you confirm if the comment by @ervibern serves as a workaround for you? It's odd that importing the named DataStore package from aws-amplify would cause such error so you might also have to delete node_modules, re-install your dependencies, and also try deleting your local db and allow DataStore to perform a fresh base sync.

Let me know if any of that helps.

@dpilch
Copy link
Member

dpilch commented Jan 31, 2023

We will not be adding polyfills directly to the Amplify library. React Native v0.71.0 with Hermes now includes the necessary polyfills.

The recommended course of action is to either:

  1. Upgrade to React Native v0.71.0
  2. Supply the necessary polyfills yourself with something like core-js.

@imdkbj
Copy link

imdkbj commented Mar 30, 2023

I have added polyfill but still getting the same, tried each things named export/core-js/updated amplify etc...

Lastly, I have to remove stop && clear to get it working.

@dpilch
Copy link
Member

dpilch commented Mar 30, 2023

Can you share the Amplify version and React Native version you are using?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working DataStore Related to DataStore category
Projects
None yet
Development

No branches or pull requests

7 participants