rn-fetch-blob is breaking after assemble release - android

i am using rn-fetch-blob to download the files to my local directory.
npx react-native run-android is running as expected, but after assemble release it fails.
the debug apk is also working.
here is the package.json file
"dependencies": {
"#react-navigation/native": "^6.1.2",
"#react-navigation/native-stack": "^6.9.8",
"axios": "^1.2.2",
"react": "18.1.0",
"react-native": "0.70.6",
"react-native-fs": "^2.20.0",
"react-native-safe-area-context": "^4.4.1",
"react-native-screens": "^3.18.2",
"react-native-video": "^5.2.1",
"rn-fetch-blob": "^0.12.0"
},
"devDependencies": {
"#babel/core": "^7.12.9",
"#babel/runtime": "^7.12.5",
"#react-native-community/eslint-config": "^2.0.0",
"babel-jest": "^26.6.3",
"eslint": "^7.32.0",
"jest": "^26.6.3",
"metro-react-native-babel-preset": "0.72.3",
"react-test-renderer": "18.1.0"
}
and here is the implementation of the package.
const hanldePress = async () => {
requestGet(`/getswpvideo?org_id=${envConst.orgID}`).then((res) => {
if (res?.data?.body) {
let videoLength = res?.data?.body?.length;
res?.data?.body?.forEach(async (i) => {
const nameArr = i.category_name.split("/")
const name = nameArr.pop();
if (!await RNFS.exists(`${RNFS.DownloadDirectoryPath}/${envConst.videoFolderName}/${name}`)) {
const { config, fs, } = RNFetchBlob
let options = {
fileCache: true,
addAndroidDownloads: {
useDownloadManager: true,
notification: false,
path: `${RNFS.DownloadDirectoryPath}/${envConst.videoFolderName}/${name}`,
}
}
try {
await config(options).fetch('GET', i.category_name)
videoLength--;
} catch (error) {
ToastAndroid.show('Something went wrong!!!',ToastAndroid.SHORT);
}
} else {
videoLength--;
if (videoLength === 0) {
ToastAndroid.show('Download Complete',ToastAndroid.SHORT);
}
}
})
}
})
}
error on android studio logcat:

Related

KeepAwake Module - Cannot find type '' in scope

Issue
I am working with a react-native codebase that has been ejected. This codebases libraries were very far out of date. I have done an npm outdate check and update every package. This is because it was a nightmare working with old libraries and builds in xcode were unreliable along with the fact our app would no longer work as expected.
Question
Upon updating I got many build errors in xCode that I have been resolving one by one. I am now stumped on this error, has anyone seen this before?:
Cannot find type 'Module' in scope <-- this is found in the "KeepAwakeModule".
There are many other errors like this, but this is the top one.
I put the contents of this file at the bottom.
I tried googling this but no luck. Its seems like the expocoremodules are not importing the keepawake module or that module does have any of the other items available. I did do a fresh pod install and yarn install as well as cleared my builds but no luck. i am providing the keep awake module along with my .Podfile and both delegate files below
Here are the files
Package.json before
{
"scripts": {
"start": "react-native start",
"android": "react-native run-android",
"ios": "react-native run-ios",
"web": "expo start --web",
"eject": "expo eject",
"build:ios": "react-native bundle — entry-file index.js — platform ios — dev false — bundle-output ios/main.jsbundle — assets-dest ios"
},
"dependencies": {
"#expo/vector-icons": "^10.0.0",
"#gregfrench/react-native-wheel-picker": "^1.2.14",
"#react-native-community/datetimepicker": "^3.0.9",
"#react-native-community/masked-view": "0.1.10",
"#react-native-community/push-notification-ios": "^1.7.1",
"#react-native-firebase/app": "^8.4.7",
"#react-native-firebase/messaging": "^7.9.1",
"#react-native-picker/picker": "^1.16.1",
"#reduxjs/toolkit": "^1.4.0",
"#sentry/react-native": "^3.2.10",
"axios": "^0.15.0",
"buffer": "^6.0.2",
"expo": "~39.0.2",
"expo-barcode-scanner": "~9.0.0",
"expo-camera": "~9.0.0",
"expo-device": "~2.3.0",
"expo-image-manipulator": "~8.3.0",
"expo-image-picker": "~9.1.1",
"expo-media-library": "~9.2.1",
"expo-notifications": "0.8.2",
"expo-permissions": "~9.3.0",
"expo-secure-store": "~9.2.0",
"expo-splash-screen": "~0.6.1",
"expo-sqlite": "~8.4.0",
"expo-status-bar": "~1.0.2",
"expo-updates": "~0.3.3",
"formik": "^2.2.9",
"lodash": "^4.17.21",
"moment": "^2.29.0",
"react": "16.13.1",
"react-axios": "2.0.3",
"react-dom": "16.13.1",
"react-native": "0.63.4",
"react-native-appearance": "^0.3.4",
"react-native-background-actions": "^2.6.1",
"react-native-background-fetch": "^4.0.2",
"react-native-ble-plx": "^2.0.3",
"react-native-calendars": "^1.403.0",
"react-native-device-info": "^8.1.3",
"react-native-elements": "^2.3.2",
"react-native-fast-image": "^8.3.4",
"react-native-gesture-handler": "~1.7.0",
"react-native-image-slider-box": "^1.0.12",
"react-native-image-zoom-viewer": "^3.0.1",
"react-native-keyboard-aware-scrollview": "^2.1.0",
"react-native-permissions": "^3.0.5",
"react-native-push-notification": "^6.1.3",
"react-native-reanimated": "~1.13.0",
"react-native-safe-area-context": "3.1.4",
"react-native-screens": "~2.10.1",
"react-native-snap-carousel": "^3.9.1",
"react-native-switch": "^2.0.0",
"react-native-unimodules": "~0.11.0",
"react-native-web": "0.14.0",
"react-native-webview": "^10.8.2",
"react-native-wheel-picker-android": "^2.0.6",
"react-navigation": "^4.4.3",
"react-navigation-stack": "^2.9.0",
"react-redux": "^7.2.2",
"rn-fetch-blob": "^0.12.0",
"toggle-switch-react-native": "^2.3.0"
},
"devDependencies": {
"#babel/core": "~7.9.0",
"babel-jest": "~25.2.6",
"jest": "~25.2.6",
"prettier": "^2.5.1",
"react-test-renderer": "~16.13.1",
"typescript": "~3.9.2"
},
"private": true,
"name": "pdi-app-v2",
"version": "1.0.0"
}
Package.json After:
{
"scripts": {
"start": "react-native start",
"android": "react-native run-android",
"ios": "react-native run-ios",
"web": "expo start --web",
"eject": "expo eject",
"build:ios": "react-native bundle — entry-file index.js — platform ios — dev false — bundle-output ios/main.jsbundle — assets-dest ios"
},
"dependencies": {
"#expo/vector-icons": "^13.0.0",
"#gregfrench/react-native-wheel-picker": "^1.2.16",
"#react-native-community/datetimepicker": "^6.7.3",
"#react-native-community/masked-view": "0.1.10",
"#react-native-community/push-notification-ios": "^1.10.1",
"#react-native-firebase/app": "^17.0.0",
"#react-native-firebase/messaging": "^17.0.0",
"#react-native-picker/picker": "^2.4.8",
"#reduxjs/toolkit": "^1.9.2",
"#sentry/react-native": "^4.14.0",
"axios": "^1.3.2",
"buffer": "^6.0.3",
"expo": "^47.0.0",
"expo-barcode-scanner": "~12.1.0",
"expo-camera": "~13.1.0",
"expo-device": "^5.0.0",
"expo-image-manipulator": "~11.0.0",
"expo-image-picker": "~14.1.0",
"expo-media-library": "~15.0.0",
"expo-notifications": "^0.17.0",
"expo-permissions": "~14.0.0",
"expo-secure-store": "~12.0.0",
"expo-splash-screen": "^0.17.5",
"expo-sqlite": "~11.0.0",
"expo-status-bar": "~1.4.2",
"expo-updates": "^0.15.6",
"formik": "^2.2.9",
"lodash": "^4.17.21",
"moment": "^2.29.4",
"react": "18.2.0",
"react-axios": "^2.0.6",
"react-dom": "18.2.0",
"react-native": "^0.71.2",
"react-native-appearance": "^0.3.4",
"react-native-background-actions": "^3.0.0",
"react-native-background-fetch": "^4.1.8",
"react-native-ble-plx": "^2.0.3",
"react-native-calendars": "^1.1293.0",
"react-native-device-info": "^10.3.0",
"react-native-elements": "^3.4.3",
"react-native-fast-image": "^8.6.3",
"react-native-gesture-handler": "~2.9.0",
"react-native-image-slider-box": "^2.0.7",
"react-native-image-zoom-viewer": "^3.0.1",
"react-native-keyboard-aware-scrollview": "^2.1.0",
"react-native-permissions": "^3.6.1",
"react-native-push-notification": "^8.1.1",
"react-native-reanimated": "^2.14.4",
"react-native-safe-area-context": "4.5.0",
"react-native-screens": "~3.19.0",
"react-native-snap-carousel": "^3.9.1",
"react-native-switch": "^2.0.0",
"react-native-unimodules": "^0.14.10",
"react-native-web": "^0.18.12",
"react-native-webview": "^11.26.1",
"react-native-wheel-picker-android": "^2.0.6",
"react-navigation": "^4.4.3",
"react-navigation-stack": "^2.9.0",
"react-redux": "^8.0.5",
"rn-fetch-blob": "^0.12.0",
"toggle-switch-react-native": "^3.3.0"
},
"devDependencies": {
"#babel/core": "~7.20.12",
"babel-jest": "~29.4.1",
"jest": "^29.4.1",
"prettier": "^2.8.3",
"react-test-renderer": "~18.2.0",
"typescript": "~4.9.5"
},
"private": true,
"name": "pdi-app-v2",
"version": "1.0.0"
}
AppDelegate.h
#import <UserNotifications/UNUserNotificationCenter.h>
#import <Expo/Expo.h>
#import <Foundation/Foundation.h>
#import <EXUpdates/EXUpdatesAppController.h>
#import <React/RCTBridgeDelegate.h>
#import <UIKit/UIKit.h>
#import <UMCore/UMAppDelegateWrapper.h>
#interface AppDelegate : UMAppDelegateWrapper <RCTBridgeDelegate, EXUpdatesAppControllerDelegate, UNUserNotificationCenterDelegate>
#end
AppDelegate.m
#import <Firebase.h>
#import "AppDelegate.h"
#import <UserNotifications/UserNotifications.h>
#import <RNCPushNotificationIOS.h>
#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import <TSBackgroundFetch/TSBackgroundFetch.h>
#if RCT_DEV
#import <React/RCTDevLoadingView.h>
#endif
#import <UMCore/UMModuleRegistry.h>
#import <UMReactNativeAdapter/UMNativeModulesProxy.h>
#import <UMReactNativeAdapter/UMModuleRegistryAdapter.h>
#import <EXSplashScreen/EXSplashScreenService.h>
#import <UMCore/UMModuleRegistryProvider.h>
#ifdef FB_SONARKIT_ENABLED
#import <FlipperKit/FlipperClient.h>
#import <FlipperKitLayoutPlugin/FlipperKitLayoutPlugin.h>
#import <FlipperKitUserDefaultsPlugin/FKUserDefaultsPlugin.h>
#import <FlipperKitNetworkPlugin/FlipperKitNetworkPlugin.h>
#import <SKIOSNetworkPlugin/SKIOSNetworkAdapter.h>
#import <FlipperKitReactPlugin/FlipperKitReactPlugin.h>
static void InitializeFlipper(UIApplication *application) {
FlipperClient *client = [FlipperClient sharedClient];
SKDescriptorMapper *layoutDescriptorMapper = [[SKDescriptorMapper alloc] initWithDefaults];
[client addPlugin:[[FlipperKitLayoutPlugin alloc] initWithRootNode:application withDescriptorMapper:layoutDescriptorMapper]];
[client addPlugin:[[FKUserDefaultsPlugin alloc] initWithSuiteName:nil]];
[client addPlugin:[FlipperKitReactPlugin new]];
[client addPlugin:[[FlipperKitNetworkPlugin alloc] initWithNetworkAdapter:[SKIOSNetworkAdapter new]]];
[client start];
}
#endif
#interface AppDelegate () <RCTBridgeDelegate>
#property (nonatomic, strong) UMModuleRegistryAdapter *moduleRegistryAdapter;
#property (nonatomic, strong) NSDictionary *launchOptions;
#end
#implementation AppDelegate
// Required for the register event.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
[RNCPushNotificationIOS didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
// Required for the notification event. You must call the completion handler after handling the remote notification.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
[RNCPushNotificationIOS didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
// Required for the registrationError event.
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
[RNCPushNotificationIOS didFailToRegisterForRemoteNotificationsWithError:error];
}
// Required for localNotification event
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void (^)(void))completionHandler
{
[RNCPushNotificationIOS didReceiveNotificationResponse:response];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
#ifdef FB_SONARKIT_ENABLED
InitializeFlipper(application);
#endif
self.moduleRegistryAdapter = [[UMModuleRegistryAdapter alloc] initWithModuleRegistryProvider:[[UMModuleRegistryProvider alloc] init]];
self.launchOptions = launchOptions;
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
#ifdef DEBUG
[self initializeReactNativeApp];
#else
EXUpdatesAppController *controller = [EXUpdatesAppController sharedInstance];
controller.delegate = self;
[controller startAndShowLaunchScreen:self.window];
#endif
[super application:application didFinishLaunchingWithOptions:launchOptions];
if([FIRApp defaultApp] == nil) {
[FIRApp configure];
}
NSURL *jsCodeLocation;
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:#"index"];
RCTBridge *bridge = [[RCTBridge alloc] initWithBundleURL:jsCodeLocation
moduleProvider:nil
launchOptions:launchOptions];
#if RCT_DEV
[bridge moduleForClass:[RCTDevLoadingView class]];
#endif
RCTRootView *rootView = [self.reactDelegate createRootViewWithBridge:bridge
moduleName:#"Test"
initialProperties:nil];
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[[TSBackgroundFetch sharedInstance] didFinishLaunching];
return YES;
}
//Called when a notification is delivered to a foreground app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
if (#available(iOS 14.0, *)) {
completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionBanner | UNNotificationPresentationOptionBadge);
} else {
// Fallback on earlier versions
completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
}
}
- (RCTBridge *)initializeReactNativeApp
{
RCTBridge *bridge = [self.reactDelegate createBridgeWithDelegate:self launchOptions:self.launchOptions];
RCTRootView *rootView = [self.reactDelegate createRootViewWithBridge:bridge moduleName:#"main" initialProperties:nil];
rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
UIViewController *rootViewController = [self.reactDelegate createRootViewController];
rootViewController.view = rootView;
self.window.rootViewController = rootViewController;
[self.window makeKeyAndVisible];
return bridge;
}
- (NSArray<id<RCTBridgeModule>> *)extraModulesForBridge:(RCTBridge *)bridge
{
NSArray<id<RCTBridgeModule>> *extraModules = [_moduleRegistryAdapter extraModulesForBridge:bridge];
// If you'd like to export some custom RCTBridgeModules that are not Expo modules, add them here!
return extraModules;
}
- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge {
#ifdef DEBUG
return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:#"index"];
#else
return [[EXUpdatesAppController sharedInstance] launchAssetUrl];
#endif
}
- (void)appController:(EXUpdatesAppController *)appController didStartWithSuccess:(BOOL)success {
appController.bridge = [self initializeReactNativeApp];
EXSplashScreenService *splashScreenService = (EXSplashScreenService *)[UMModuleRegistryProvider getSingletonModuleForClass:[EXSplashScreenService class]];
[splashScreenService showSplashScreenFor:self.window.rootViewController];
}
#end
PodFile
require File.join(File.dirname(`node --print "require.resolve('expo/package.json')"`), "scripts/autolinking")
require File.join(File.dirname(`node --print "require.resolve('react-native/package.json')"`), "scripts/react_native_pods")
require File.join(File.dirname(`node --print "require.resolve('#react-native-community/cli-platform-ios/package.json')"`), "native_modules")
pod 'Firebase', :modular_headers => true
pod 'FirebaseCore', :modular_headers => true
pod 'GoogleUtilities', :modular_headers => true
$RNFirebaseAsStaticFramework = true
require 'json'
podfile_properties = JSON.parse(File.read(File.join(__dir__, 'Podfile.properties.json'))) rescue {}
platform :ios, podfile_properties['ios.deploymentTarget'] || '13.0'
install! 'cocoapods',
:deterministic_uuids => false
target 'pdimobile' do
use_expo_modules!
config = use_native_modules!
use_frameworks! :linkage => podfile_properties['ios.useFrameworks'].to_sym if podfile_properties['ios.useFrameworks']
# Flags change depending on the env values.
flags = get_default_flags()
use_flipper! # should match the version of your Flipper client app
use_react_native!(
:path => config[:reactNativePath],
:hermes_enabled => podfile_properties['expo.jsEngine'] == 'hermes',
:fabric_enabled => flags[:fabric_enabled],
# An absolute path to your application root.
:app_path => "#{Pod::Config.instance.installation_root}/..",
)
post_install do |installer|
flipper_post_install(installer)
react_native_post_install(
installer,
# Set `mac_catalyst_enabled` to `true` in order to apply patches
# necessary for Mac Catalyst builds
:mac_catalyst_enabled => false
)
__apply_Xcode_12_5_M1_post_install_workaround(installer)
# This is necessary for Xcode 14, because it signs resource bundles by default
# when building for devices.
installer.target_installation_results.pod_target_installation_results
.each do |pod_name, target_installation_result|
target_installation_result.resource_bundle_targets.each do |resource_bundle_target|
resource_bundle_target.build_configurations.each do |config|
config.build_settings['CODE_SIGNING_ALLOWED'] = 'NO'
end
end
end
end
permissions_path = '../node_modules/react-native-permissions/ios'
pod 'Permission-BluetoothPeripheral', :path => "#{permissions_path}/BluetoothPeripheral"
pod 'Permission-Camera', :path => "#{permissions_path}/Camera"
pod 'Permission-Notifications', :path => "#{permissions_path}/Notifications"
pod 'Permission-PhotoLibrary', :path => "#{permissions_path}/PhotoLibrary"
post_integrate do |installer|
begin
expo_patch_react_imports!(installer)
rescue => e
Pod::UI.warn e
end
begin
expo_patch_react_imports!(installer)
rescue => e
Pod::UI.warn e
end
end
end
Keep Awake Module
// Copyright 2021-present 650 Industries. All rights reserved.
import ExpoModulesCore
public final class KeepAwakeModule: Module {
private var activeTags = Set<String>()
public func definition() -> ModuleDefinition {
Name("ExpoKeepAwake")
AsyncFunction("activate") { (tag: String) -> Bool in
if self.activeTags.isEmpty {
setActivated(true)
}
self.activeTags.insert(tag)
return true
}
AsyncFunction("deactivate") { (tag: String) -> Bool in
self.activeTags.remove(tag)
if self.activeTags.isEmpty {
setActivated(false)
}
return true
}
AsyncFunction("isActivated") { () -> Bool in
return DispatchQueue.main.sync {
return UIApplication.shared.isIdleTimerDisabled
}
}
OnAppEntersForeground {
if !self.activeTags.isEmpty {
setActivated(true)
}
}
OnAppEntersBackground {
if !self.activeTags.isEmpty {
setActivated(false)
}
}
}
}
private func setActivated(_ activated: Bool) {
DispatchQueue.main.async {
UIApplication.shared.isIdleTimerDisabled = activated
}
}
I did create a new bare react-native project just to see that libraries being used and to ensure there were not file structure changes needed with my upgrade. I do notice the AppDelegate files are now in a builds folder and the .m has a new extension .mm Could this be more problem? If so, how do I properly configure my codebase to support this?

Receiving Proxy error: Error occurred while proxying request [ECONNREFUSED] in react app

I have a react application that is making API calls through axios to my backend and I am receiving the error
[HPM] Error occurred while proxying request matt.hearthdisplay.com:3000/api/user/my to http://localhost:8000/ [ECONNREFUSED] (https://nodejs.org/api/errors.html#errors_common_system_errors)
I am not even calling proxy in my package.json so I am not sure why it's even attempting this? For context the API GET requests are working on my coworker's machines with the same code and I have recently moved to a new location with a different wifi router so I am not sure if this is a computer-specific problem.
matt.hearthdisplay.com:3000/api/user/my is my front end react app and http://localhost:8000/ is for my backend.
What could be causing this? I am on a Macbook M1 running Mac OS Montery 12.3 below are my files that should help. I have tried everything online I have found...
API Request thats producing the error
useEffect(() => {
async function inner() {
const response = await axiosClient.get(`/user/my`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
if (response.status === 200) {
setFormState({
firstName: response.data.user.first_name,
lastName: response.data.user.last_name,
});
}
}
if (!!token) {
inner();
}
}, [token]);
axiosCLient.ts
import axios, { AxiosResponse } from "axios";
import { apiRoot } from "./variables";
const axiosClient = axios.create({
baseURL: apiRoot,
});
// Timeout in 3 seconds by default
axiosClient.defaults.timeout = 3000;
function handle2xxResponse(response: AxiosResponse<any>): AxiosResponse<any> {
return response;
}
axiosClient.interceptors.response.use(handle2xxResponse);
export default axiosClient;
package.json
{
"name": "webapp",
"version": "0.1.0",
"private": true,
"dependencies": {
"#emotion/react": "^11.7.1",
"#emotion/styled": "^11.6.0",
"#fortawesome/fontawesome-svg-core": "^1.2.36",
"#fortawesome/free-solid-svg-icons": "^5.15.4",
"#fortawesome/react-fontawesome": "^0.1.16",
"#fullhuman/postcss-purgecss": "^4.1.3",
"#mui/icons-material": "^5.2.4",
"#mui/material": "^5.2.4",
"#mui/styled-engine-sc": "^5.1.0",
"#sentry/react": "^6.16.1",
"#sentry/tracing": "^6.16.1",
"#testing-library/jest-dom": "^5.11.4",
"#testing-library/react": "^11.1.0",
"#testing-library/user-event": "^12.1.10",
"#types/jest": "^26.0.15",
"#types/node": "^12.0.0",
"#types/react": "^17.0.0",
"#types/react-dom": "^17.0.0",
"#types/react-lottie": "^1.2.6",
"axios": "^0.24.0",
"http-proxy-middleware": "^2.0.3",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-hook-form": "^7.21.2",
"react-lottie": "^1.2.3",
"react-native-dropdown": "^0.0.6",
"react-router-dom": "^6.0.2",
"react-scripts": "4.0.3",
"styled-components": "^5.3.3",
"tailwindcss": "^2.2.19",
"typescript": "^4.1.2",
"web-vitals": "^1.0.1",
"zustand": "^3.6.5"
},
"scripts": {
"build:tailwind": "postcss src/styles/index.tailwind.css -o src/styles/index.css",
"watch:tailwind": "postcss -w src/styles/index.tailwind.css -o src/styles/index.css",
"start": "run-p watch:tailwind start:react",
"start:react": "react-scripts start",
"prebuild": "npm run build:tailwind",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"autoprefixer": "^10.4.0",
"npm-run-all": "^4.1.5",
"postcss": "^8.4.4",
"postcss-cli": "^9.0.2"
}
}
setUpProxy.js
const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = function (app) {
app.use(
createProxyMiddleware("/api", {
target: "http://localhost:8000",
changeOrigin: true,
secure: false,
})
);
};
Trying add the following header in the proxy code;
target: "http://localhost:8000",
headers: {
"Connection": "keep-alive"
},
...
The Keep-Alive general header allows the sender to hint about how the connection may be used to set a timeout and a maximum amount of requests.

React Native firebase realtime database not working

I'm trying to use Firebase realtime database on my React Native project. Based on the documentation I did following things on Android side(I'm checking for Android).
yarn add #react-native-firebase/app
Then put the google-services.json and did all gradle related changes.
yarn add #react-native-firebase/database
I have created a small test db as well to test the functionality.
This is the code that I have tried on my home page.
componentDidMount() {
console.log("Component Did Mount")
database()
.ref('name/')
.on('value', snapshot => {
console.log('User data: ', snapshot);
});
}
'User data' has not been printed in console. Not only the snapshot values but also user data text. Only 'component did mount' text is printed in console there. I added all the relevant permissions in AndroidMainifest as well
AndroidManifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
package json
"dependencies": {
"#react-native-async-storage/async-storage": "^1.15.5",
"#react-native-community/masked-view": "^0.1.11",
"#react-native-firebase/app": "^12.7.5",
"#react-native-firebase/database": "^12.7.5",
"#react-native-firebase/firestore": "^12.7.5",
"#react-native-firebase/remote-config": "^12.8.0",
"#react-navigation/bottom-tabs": "^5.11.11",
"#react-navigation/native": "^5.9.4",
"#react-navigation/stack": "^5.14.5",
"#reduxjs/toolkit": "^1.6.0",
"#thecodingmachine/redux-toolkit-wrapper": "2.0.1",
"axios": "^0.21.1",
"i18next": "^20.3.2",
"prop-types": "^15.7.2",
"react": "17.0.1",
"react-i18next": "^11.11.0",
"react-native": "0.64.2",
"react-native-flipper": "^0.94.1",
"react-native-gesture-handler": "^1.10.3",
"react-native-linear-gradient": "^2.5.6",
"react-native-reanimated": "^2.2.0",
"react-native-safe-area-context": "^3.2.0",
"react-native-screens": "^3.4.0",
"react-native-webview": "^11.13.0",
"react-redux": "^7.2.4",
"redux": "^4.1.0",
"redux-flipper": "^1.4.2",
"redux-persist": "^6.0.0"
},
"devDependencies": {
"#babel/core": "^7.12.9",
"#babel/runtime": "^7.12.5",
"#react-native-community/eslint-config": "^2.0.0",
"babel-jest": "^26.6.3",
"babel-plugin-module-resolver": "^4.0.0",
"eslint": "^7.22.0",
"eslint-import-resolver-babel-module": "^5.1.2",
"eslint-plugin-import": "^2.22.0",
"eslint-plugin-jest": "^24.3.5",
"identity-obj-proxy": "^3.0.0",
"jest": "^26.6.3",
"metro-react-native-babel-preset": "^0.64.0",
"react-test-renderer": "17.0.1"
},
I'm using this boilerplate
https://github.com/thecodingmachine/react-native-boilerplate
The DatabaseReference#on() method accepts two separate callbacks, one for when the requested event fires and one that handles errors.
database()
.ref('name') // no trailing "/"! (even though it does get trimmed off internally)
.on(
'value',
snapshot => {
console.log('Latest value for "/name": ', snapshot);
},
error => {
console.error('Failed to retrieve "/name": ', snapshot);
}
);
Importantly, this method also returns the first snapshot-listening callback, so that you can use it with DatabaseReference#off when unmounting your component.
const nameListener = database()
.ref('name')
.on(/* ... */);
// create a callback to be called in the `componentWillUnmount()` method
const unsubscribeNameListener = () => nameRef.off('value', nameListener);
Rolling this together gives:
class NameFromDatabase extends React.Component {
private unsubscribers = [];
componentDidMount() {
const nameRef = database().ref('name');
const nameListener = nameRef
.on(
'value',
snapshot => {
console.log('Latest value for "/name": ', snapshot);
},
error => {
console.error('Failed to retrieve "/name": ', snapshot);
}
);
// create a callback to be called in the `componentWillUnmount()` method
unsubscribers.push(() => nameRef.off('value', nameListener));
}
componentWillUnmount() {
unsubscribers.forEach(unsub => unsub());
}
}
Although the above code works, you really should make use of the React Hooks API and the new Firebase SDK's Modular API instead. Using the class-based form of React and namespace-based version of Firebase is ill-advised for new projects.
import { useState, useEffect } from 'react';
import { getDatabase, ref, onValue, off } from 'firebase/database';
const NameFromDatabase = () => {
const [name, setName] = useState();
useEffect(() => {
const nameRef = ref(getDatabase(), 'name');
// onValue returns its own unsubscribe function
return onValue(
nameRef,
snapshot => {
console.log('Latest value for "/name": ', snapshot.val());
setName(snapshot.val());
},
error => {
console.error('Failed to retrieve "/name": ', error);
setName(null);
}
);
}
if (name === void 0)
return (<div>Loading...</div>);
if (name === null)
return (<div class="error">Name not found!</div>);
return (<div>{ name }</div>);
}

TypeError: Cannot read property 'getToken' of undefined in Ionic3 project

I tried to use the latest version of cordova-plugin-firebasex for my ionic3 app. I also did refer the ionic3 example for firebasex plugin. But after adding the code, I am getting the error as 'TypeError: Cannot read property 'getToken' of undefined'. Below is the code which I have used:
In my login.ts file:
if ( this.accessToken ) {
this.fireBaseService.getFirebaseXToken();
}
In my firebase-service.ts file===**====
export class FireBaseService {
protected token:any;
public firebasePlugin;
async getFirebaseXToken() {
let token;
this.firebasePlugin = (window).FirebasePlugin;
token = await this.firebasePlugin.getToken(token => {
console.log('Response from getToken===>>>>',token);
});
}
}
These are the specs for my ionic3 project:
"cordova": "^9.0.0",
"cordova-android": "8.1.0",
"cordova-plugin-firebasex": "^8.1.1",
"cordova-android-play-services-gradle-release": "3.0.0",
"cordova-android-support-gradle-release": "^3.0.0",
"cordova-plugin-androidx": "^1.0.2",
"cordova-plugin-androidx-adapter": "1.1.0",
"devDependencies": {
"#ionic/app-scripts": "^3.2.2",
"typescript": "~2.6.2"
}
If there are any changes to be done in my code, am I missing something, any kind of help will be helpful. Thanks.

Platform specific testing using Jest on a React Native app

This is the react native component
//Test.js
export default class Test extends Component {
render() {
return(
<View>
</Animated.View> {
Platform.OS === 'android' &&
<TouchableNativeFeedback>
// some android specific code
</TouchableNativeFeedback>
}</Animated.View>
</View>
)
}
}
THis is the test case;
//testcases.js
import { Text, TouchableOpacity, Platform } from 'react-native';
import React from 'react';
import ReactDOM from 'react-dom';
import { shallow } from 'enzyme';
import Test from '../Test'
describe('Testing an App', () => {
let snapshot;
beforeAll(() => {
snapshot = shallow(<Test />);
Platform.OS = 'android';
});
it(' -- must return 1', () => {
expect(snapshot.find('TouchableNativeFeedback').length).toBe(1);
});
});
While the expected return is 1; The received value is 0; I have set up Platform as 'android' and yet no luck.
I am new to Mobile automation testing; Hence I could be missing something obvious. Should I use react-dom to render and test further?
I feel it's something very obvious, but can't get my finger on it.
This is my package.json
{
"name": "exampleApp",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"react": "15.4.1",
"react-native": "0.42.3"
},
"devDependencies": {
"babel-jest": "20.0.3",
"babel-preset-react-native": "2.0.0",
"jest": "20.0.4",
"enzyme" : "2.8.0",
"react-dom": "15.4.1",
"react-addons-test-utils":"15.4.1",
"react-test-renderer": "15.4.1"
},
"jest": {
"preset": "react-native"
}
}
You can not change your platform directly in your test. You need to set the desired platform in your settings. Take a look at this documentation to see how to do it.

Categories

Resources