react-native-firebase icon indicating copy to clipboard operation
react-native-firebase copied to clipboard

Listening to add and update new docs is not working

Open ahmadzraiq opened this issue 3 years ago • 5 comments

Issue

I want listen to new and update user conversations, NOT to the old conversations

I've tried two things but none of them work

First one I made the listener to listen to new and update docs depend on createdAt

    const ref = await firestore()
      .collection("conversations")
      .where("members", "array-contains", user?.id + "")
      .where("createdAt", ">=", firestore.Timestamp.fromMillis(Date.now()));

    const listener = ref.onSnapshot(conversations => {
      // append new messages to message array
      conversations.docChanges().forEach(async m => {
        console.log("line 116 ~ conversations.docChanges ~ m", m);
      });
    }); 

Second one I've got a last conversion id and passed that to the listener like this

    const ref = await firestore()
      .collection("conversations")
      .where("members", "array-contains", user?.id + "");

    const lastConversation = await ref.orderBy("createdAt", "desc").limit(1).get();

    const listener = ref
      .orderBy("createdAt")
      .startAt(lastConversation?.docs[0].id)
      .onSnapshot(conversations => {
        // append new messages to message array
        conversations.docChanges().forEach(async m => {
          console.log("line 116 ~ conversations.docChanges ~ m", m);
        });
      });

The only thing that's working with me, if I listen to whole conversations

The problem here it will return all conversations in the first time

  const ref = await firestore()
      .collection("conversations")
      .where("members", "array-contains", user?.id + "");

    const listener = ref.onSnapshot(conversations => {
    console.log("line 111 ~ listener ~ conversations", conversations)

    });


Project Files

Javascript

Click To Expand

package.json:

{
  "main": "index.js",
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "wm-d": "watchman watch-del-all",
    "android-dev": "react-native run-android --variant=devdebug --appIdSuffix=dev",
    "android-prod": "react-native run-android --variant=proddebug",
    "ios-dev": "react-native run-ios  --scheme 'swiitchDev' --configuration DebugDev",
    "ios-prod": "react-native run-ios  --scheme 'swiitch' --configuration Debug",
    "code-push-prod": "appcenter codepush release-react -a Swiitch/swiitch-ios -d Production -m && appcenter codepush release-react -a Swiitch/swiitch-android -d Production -m",
    "code-push-dev": "appcenter codepush release-react -a Swiitch/swiitch-ios -d Staging  -m && appcenter codepush release-react -a Swiitch/swiitch-android -d Staging -m",
    "test": "jest",
    "postinstall": "patch-package",
    "lint": "eslint --fix --ext .js,.jsx ."
  },
  "dependencies": {
    "@codler/react-native-keyboard-aware-scroll-view": "^2.0.1",
    "@gorhom/portal": "^1.0.14",
    "@invertase/react-native-apple-authentication": "^2.2.2",
    "@react-native-clipboard/clipboard": "^1.10.0",
    "@react-native-community/async-storage": "~1.12.0",
    "@react-native-community/checkbox": "^0.5.12",
    "@react-native-community/netinfo": "^9.3.0",
    "@react-native-community/picker": "^1.8.1",
    "@react-native-firebase/analytics": "^14.11.0",
    "@react-native-firebase/app": "^14.11.0",
    "@react-native-firebase/crashlytics": "^14.11.0",
    "@react-native-firebase/dynamic-links": "^14.11.0",
    "@react-native-firebase/firestore": "^14.11.0",
    "@react-native-firebase/messaging": "^14.11.0",
    "@react-native-google-signin/google-signin": "^8.0.0",
    "@react-native-masked-view/masked-view": "^0.2.7",
    "@react-navigation/bottom-tabs": "^6.3.2",
    "@react-navigation/drawer": "^6.4.3",
    "@react-navigation/elements": "^1.3.4",
    "@react-navigation/material-top-tabs": "^6.2.2",
    "@react-navigation/native": "^6.0.11",
    "@react-navigation/stack": "^6.2.2",
    "axios": "^0.18.0",
    "formik": "^2.2.9",
    "i18next": "^21.8.14",
    "lodash": "^4.17.21",
    "lottie-react-native": "^5.1.3",
    "mixpanel-react-native": "^1.5.0",
    "moment": "^2.29.4",
    "native-base": "^3.4.9",
    "query-string": "^7.1.1",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-i18next": "^11.18.1",
    "react-native": "0.69.2",
    "react-native-adjust": "^4.29.6",
    "react-native-autocomplete-input": "^5.1.0",
    "react-native-code-push": "^7.0.4",
    "react-native-config": "^1.4.6",
    "react-native-device-info": "^10.0.2",
    "react-native-fast-image": "^8.5.11",
    "react-native-fbsdk-next": "^10.0.0",
    "react-native-fs": "^2.20.0",
    "react-native-geolocation-service": "^5.3.0",
    "react-native-gesture-handler": "^2.5.0",
    "react-native-google-places-autocomplete": "^2.4.1",
    "react-native-hyperlink": "^0.0.19",
    "react-native-image-pan-zoom": "^2.1.12",
    "react-native-image-picker": "^4.8.4",
    "react-native-image-zoom-viewer": "^3.0.1",
    "react-native-in-app-message": "^1.0.33",
    "react-native-inappbrowser-reborn": "^3.6.3",
    "react-native-keyboard-aware-scroll-view": "^0.9.5",
    "react-native-linear-gradient": "^2.6.2",
    "react-native-loading-spinner-overlay": "^2.0.0",
    "react-native-maps": "^1.0.3",
    "react-native-modalize": "^2.0.13",
    "react-native-option-menu": "^1.1.3",
    "react-native-pager-view": "^5.4.25",
    "react-native-permissions": "^3.6.0",
    "react-native-qrcode-svg": "^6.1.2",
    "react-native-ratings": "^8.1.0",
    "react-native-reanimated": "^2.9.1",
    "react-native-redash": "^18.0.0",
    "react-native-responsive-fontsize": "^0.5.1",
    "react-native-restart": "0.0.24",
    "react-native-safe-area-context": "4.3.1",
    "react-native-screens": "~3.15.0",
    "react-native-share": "^7.6.6",
    "react-native-shared-element": "^0.8.4",
    "react-native-skeleton-placeholder": "^5.0.0",
    "react-native-snap-carousel": "^4.0.0-beta.6",
    "react-native-splash-screen": "^3.3.0",
    "react-native-status-bar-height": "^2.6.0",
    "react-native-svg": "^12.4.0",
    "react-native-swiper": "^1.6.0",
    "react-native-tab-view": "^3.1.1",
    "react-native-toast-message": "^2.1.5",
    "react-native-tracking-transparency": "^0.1.1",
    "react-native-vector-icons": "^9.2.0",
    "react-native-video": "^6.0.0-alpha.1",
    "react-native-view-shot": "^3.3.0",
    "react-native-webview": "^11.22.7",
    "react-navigation-shared-element": "^3.1.3",
    "react-redux": "^8.0.2",
    "recombee-js-api-client": "^4.0.0",
    "redux": "^4.2.0",
    "redux-thunk": "^2.4.1",
    "yup": "^0.32.11"
  },
  "devDependencies": {
    "@babel/core": "~7.18.9",
    "@react-native-community/eslint-config": "^3.0.3",
    "babel-jest": "~28.1.3",
    "eslint": "^8.20.0",
    "eslint-config-airbnb": "^19.0.4",
    "eslint-plugin-import": "^2.26.0",
    "eslint-plugin-jsx-a11y": "^6.6.0",
    "eslint-plugin-react": "^7.30.1",
    "eslint-plugin-react-hooks": "^4.6.0",
    "eslint-plugin-react-native": "^4.0.0",
    "jest": "~28.1.3",
    "metro-react-native-babel-preset": "^0.71.3",
    "metro-react-native-babel-transformer": "^0.71.3",
    "patch-package": "^6.4.7",
    "prettier": "^2.7.1",
    "react-native-svg-transformer": "^1.0.0",
    "react-test-renderer": "~18.2.0",
    "reactotron-react-native": "^5.0.2",
    "reactotron-redux": "^3.1.3"
  },
  "jest": {
    "preset": "react-native"
  },
  "private": true,
  "name": "swiitch"
}

firebase.json for react-native-firebase v6:

{
    "react-native": {}
}

iOS

Click To Expand

ios/Podfile:

  • [ ] I'm not using Pods
  • [x] I'm using Pods and my Podfile looks like:
require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

project 'swiitch',
    'DebugDev' => :debug,
    'Debug' => :debug,
    'ReleaseDev' => :release,
    'Release' => :release

platform :ios, '13.0'
install! 'cocoapods', :deterministic_uuids => false

production = ENV["PRODUCTION"] == "1"

target 'swiitch' do

  rn_maps_path = '../node_modules/react-native-maps'
  pod 'react-native-google-maps', :path => rn_maps_path
  pod 'GoogleMaps'
  pod 'Google-Maps-iOS-Utils'
  pod 'GoogleSignIn', '~> 6.2.2'

  permissions_path = '../node_modules/react-native-permissions/ios'
  pod 'Permission-Camera', :path => "#{permissions_path}/Camera"
  pod 'Permission-PhotoLibrary', :path => "#{permissions_path}/PhotoLibrary"

  config = use_native_modules!

  # Flags change depending on the env values.
  flags = get_default_flags()

  use_react_native!(
    :path => config[:reactNativePath],
    :production => production,
    # to enable hermes on iOS, change `false` to `true` and then install pods
    :hermes_enabled => true,
    :fabric_enabled => flags[:fabric_enabled],
    :flipper_configuration => FlipperConfiguration.enabled,
    # An absolute path to your application root.
    :app_path => "#{Pod::Config.instance.installation_root}/.."
  )


    post_install do |installer|
      react_native_post_install(installer)
      __apply_Xcode_12_5_M1_post_install_workaround(installer)
  end
end

target 'ImageNotification' do
  pod 'Firebase/Messaging', '~> 8.15.0'
end

AppDelegate.mm:

#import "AppDelegate.h"

#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>

#import <React/RCTAppSetupUtils.h>

#import <React/RCTLinkingManager.h>

#import "ReactNativeConfig.h"
#import <Firebase.h>
#import <GoogleMaps/GoogleMaps.h>
#import <RNGoogleSignin/RNGoogleSignin.h>
#import <CodePush/CodePush.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>

#if RCT_NEW_ARCH_ENABLED
#import <React/CoreModulesPlugins.h>
#import <React/RCTCxxBridgeDelegate.h>
#import <React/RCTFabricSurfaceHostingProxyRootView.h>
#import <React/RCTSurfacePresenter.h>
#import <React/RCTSurfacePresenterBridgeAdapter.h>
#import <ReactCommon/RCTTurboModuleManager.h>
#import <react/config/ReactNativeConfig.h>

static NSString *const kRNConcurrentRoot = @"concurrentRoot";

@interface AppDelegate () <RCTCxxBridgeDelegate, RCTTurboModuleManagerDelegate> {
  RCTTurboModuleManager *_turboModuleManager;
  RCTSurfacePresenterBridgeAdapter *_bridgeAdapter;
  std::shared_ptr<const facebook::react::ReactNativeConfig> _reactNativeConfig;
  facebook::react::ContextContainer::Shared _contextContainer;
}
@end
#endif

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    if ([FIRApp defaultApp] == nil) {
    [FIRApp configure];
  }

  RCTAppSetupPrepareApp(application);

   NSString *googleMapApiKey = [ReactNativeConfig envFor:@"GOOGLE_MAPS_API_KEY_IOS"];
  [GMSServices provideAPIKey:googleMapApiKey];

  [FBSDKApplicationDelegate.sharedInstance initializeSDK];

 [[FBSDKApplicationDelegate sharedInstance] application:application
                           didFinishLaunchingWithOptions:launchOptions];

  RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];

#if RCT_NEW_ARCH_ENABLED
  _contextContainer = std::make_shared<facebook::react::ContextContainer const>();
  _reactNativeConfig = std::make_shared<facebook::react::EmptyReactNativeConfig const>();
  _contextContainer->insert("ReactNativeConfig", _reactNativeConfig);
  _bridgeAdapter = [[RCTSurfacePresenterBridgeAdapter alloc] initWithBridge:bridge contextContainer:_contextContainer];
  bridge.surfacePresenter = _bridgeAdapter.surfacePresenter;
#endif

  NSDictionary *initProps = [self prepareInitialProps];
  UIView *rootView = RCTAppSetupDefaultRootView(bridge, @"main", initProps);

  if (@available(iOS 13.0, *)) {
    rootView.backgroundColor = [UIColor systemBackgroundColor];
  } else {
    rootView.backgroundColor = [UIColor whiteColor];
  }


  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  return YES;
}

/// This method controls whether the `concurrentRoot`feature of React18 is turned on or off.
///
/// @see: https://reactjs.org/blog/2022/03/29/react-v18.html
/// @note: This requires to be rendering on Fabric (i.e. on the New Architecture).
/// @return: `true` if the `concurrentRoot` feture is enabled. Otherwise, it returns `false`.
- (BOOL)concurrentRootEnabled
{
  // Switch this bool to turn on and off the concurrent root
  return true;
}
- (NSDictionary *)prepareInitialProps
{
  NSMutableDictionary *initProps = [NSMutableDictionary new];
#ifdef RCT_NEW_ARCH_ENABLED
  initProps[kRNConcurrentRoot] = @([self concurrentRootEnabled]);
#endif
  return initProps;
}

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
  return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
#else
  return [CodePush bundleURL];
#endif
}

// Linking API
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
  if ([[FBSDKApplicationDelegate sharedInstance] application:application openURL:url options:options] || [RNGoogleSignin application:application openURL:url options:options]) {
    return YES;
  }
  if ([RCTLinkingManager application:application openURL:url options:options]) {
    return YES;
  }

  return NO;
}

// Universal Links
- (BOOL)application:(UIApplication *)application continueUserActivity:(nonnull NSUserActivity *)userActivity restorationHandler:(nonnull void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler {
 return [RCTLinkingManager application:application
                  continueUserActivity:userActivity
                    restorationHandler:restorationHandler];
}

#if RCT_NEW_ARCH_ENABLED

#pragma mark - RCTCxxBridgeDelegate

- (std::unique_ptr<facebook::react::JSExecutorFactory>)jsExecutorFactoryForBridge:(RCTBridge *)bridge
{
  _turboModuleManager = [[RCTTurboModuleManager alloc] initWithBridge:bridge
                                                             delegate:self
                                                            jsInvoker:bridge.jsCallInvoker];
  return RCTAppSetupDefaultJsExecutorFactory(bridge, _turboModuleManager);
}

#pragma mark RCTTurboModuleManagerDelegate

- (Class)getModuleClassFromName:(const char *)name
{
  return RCTCoreModulesClassProvider(name);
}

- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:(const std::string &)name
                                                      jsInvoker:(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
{
  return nullptr;
}

- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:(const std::string &)name
                                                     initParams:
                                                         (const facebook::react::ObjCTurboModule::InitParams &)params
{
  return nullptr;
}

- (id<RCTTurboModule>)getModuleInstanceFromClass:(Class)moduleClass
{
  return RCTAppSetupDefaultModuleFromClass(moduleClass);
}

#endif

@end



Android

Click To Expand

Have you converted to AndroidX?

  • [ ] my application is an AndroidX application?
  • [ ] I am using android/gradle.settings jetifier=true for Android compatibility?
  • [ ] I am using the NPM package jetifier for react-native compatibility?

android/build.gradle:

// N/A

android/app/build.gradle:

// N/A

android/settings.gradle:

// N/A

MainApplication.java:

// N/A

AndroidManifest.xml:

<!-- N/A -->

Environment

Click To Expand

react-native info output:

System:
    OS: macOS 12.3.1
    CPU: (10) arm64 Apple M1 Pro
    Memory: 129.78 MB / 16.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 18.6.0 - /opt/homebrew/bin/node
    Yarn: 1.22.18 - /opt/homebrew/bin/yarn
    npm: 8.13.2 - /opt/homebrew/bin/npm
    Watchman: 2022.07.04.00 - /opt/homebrew/bin/watchman
  Managers:
    CocoaPods: 1.11.3 - /opt/homebrew/bin/pod
  SDKs:
    iOS SDK:
      Platforms: DriverKit 21.4, iOS 15.5, macOS 12.3, tvOS 15.4, watchOS 8.5
    Android SDK: Not Found
  IDEs:
    Android Studio: 2021.2 AI-212.5712.43.2112.8609683
    Xcode: 13.4.1/13F100 - /usr/bin/xcodebuild
  Languages:
    Java: 11.0.16 - /usr/bin/javac
  npmPackages:
    @react-native-community/cli: Not Found
    react: 18.2.0 => 18.2.0 
    react-native: 0.69.2 => 0.69.2 
    react-native-macos: Not Found
  npmGlobalPackages:
    *react-native*: Not Found
  • Platform that you're experiencing the issue on:
    • [ ] iOS
    • [ ] Android
    • [ ] iOS but have not tested behavior on Android
    • [ ] Android but have not tested behavior on iOS
    • [x] Both
  • react-native-firebase version you're using that has this issue:
    • e.g. 7.6.0
  • Firebase module(s) you're using that has the issue:
    • e.g. Instance ID
  • Are you using TypeScript?
    • NO

ahmadzraiq avatar Sep 07 '22 14:09 ahmadzraiq

These versions:


    "@react-native-firebase/analytics": "^10.0.0",
    "@react-native-firebase/app": "^10.0.0",
    "@react-native-firebase/crashlytics": "^10.0.0",
    "@react-native-firebase/dynamic-links": "^10.0.0",
    "@react-native-firebase/firestore": "^10.0.0",
    "@react-native-firebase/messaging": "^10.0.0",

Are about a year and a half of bugfixes and releases old. I would update to current, as reproductions on old versions typically have no value

This is dangerous!!

target 'ImageNotification' do
  pod 'Firebase/Messaging', '~> 7.6.0' # eg 6.31.0 
end

You want to define a firebase version and have both react-native-firebase and this definition share it, more like this:

https://github.com/invertase/react-native-firebase/blob/f10891a6d8079766374ceb7790a824d90306946a/tests/ios/Podfile#L6

...as described here: https://rnfirebase.io/#ios

Otherwise it's possible you are specifying incompatible versions. Downside to that is then you have to track the version along with react-native-firebase releases. It might be best to remove the version specifier entirely, then react-native-firebase will pin it with its internal dependency that has a version, and the pod here should simply align itself. You can verify that behavior by examining Podfile.lock to make sure it's the expected version from here https://github.com/invertase/react-native-firebase/blob/f10891a6d8079766374ceb7790a824d90306946a/packages/app/package.json#L68 for the version of react-native-firebase you are on

If this still reproduces on the current version, we can investigate, although it might be interesting to try to reproduce this with the firebase-js-sdk or with one of the native quickstarts to determine if the error is in an underlying SDK / is just "normal" firebase behavior or whether we have a bug here https://github.com/firebase/quickstart-ios/tree/master/firestore https://github.com/firebase/quickstart-js/tree/master/firestore

mikehardy avatar Sep 07 '22 15:09 mikehardy

@mikehardy I've switched to another branch that has newer version, I've update my environment have a look, And I think the problem isn't with firebase setup

ahmadzraiq avatar Sep 07 '22 17:09 ahmadzraiq

Okay, but that's still not actually up to date, right? I don't have a lot of time right now to reproduce this - my best advice for a rapid resolution is still:


it might be interesting to try to reproduce this with the firebase-js-sdk or with one of the native quickstarts to determine if the error is in an underlying SDK / is just "normal" firebase behavior or whether we have a bug here https://github.com/firebase/quickstart-ios/tree/master/firestore https://github.com/firebase/quickstart-js/tree/master/firestore

mikehardy avatar Sep 07 '22 19:09 mikehardy

I just want to know if what i did is right as a logic or i have missed something like indexes.

ahmadzraiq avatar Sep 07 '22 23:09 ahmadzraiq

And the answer is I don't know. I don't use firebase that way, apologies

mikehardy avatar Sep 08 '22 12:09 mikehardy

Hello 👋, to help manage issues we automatically close stale issues.

This issue has been automatically marked as stale because it has not had activity for quite some time.Has this issue been fixed, or does it still require attention?

This issue will be closed in 15 days if no further activity occurs.

Thank you for your contributions.

github-actions[bot] avatar Dec 05 '22 19:12 github-actions[bot]