facebook / react-native

A framework for building native applications using React
https://reactnative.dev
MIT License
119.19k stars 24.33k forks source link

typeerror network request failed react native android at android version < 10 #38015

Closed ferdylimmm9 closed 1 year ago

ferdylimmm9 commented 1 year ago

Description

React.useEffect(() => { async function exec() { try { //can fetch const response = await fetch('https://fakestoreapi.com/products'); const response = await fetch('https://forum-api.dicoding.dev/v1/users');

    //return typeerror network request failed and the api hasn't fetched
    const response = await fetch(
      'https://staging.petskita.com/api/user/health',
    );
    const response = await fetch(
      'https://staging.topvalas.com/api/employee/health',
    );
    const json = await response.json();
    console.log(json);
  } catch (e) {
    console.log(e, 'te');
  }
}
exec();

}, []);

React Native Version

0.71.8

Output of npx react-native info

System: OS: macOS 13.4 CPU: (8) arm64 Apple M1 Pro Memory: 328.63 MB / 16.00 GB Shell: 5.9 - /bin/zsh Binaries: Node: 18.12.0 - /usr/local/bin/node Yarn: 1.22.19 - /usr/local/bin/yarn npm: 9.6.6 - /opt/homebrew/bin/npm Watchman: 2023.06.12.00 - /opt/homebrew/bin/watchman Managers: CocoaPods: 1.12.1 - /Users/ferdylim/.gem/bin/pod SDKs: iOS SDK: Platforms: DriverKit 22.4, iOS 16.4, macOS 13.3, tvOS 16.4, watchOS 9.4 Android SDK: API Levels: 26, 28, 29, 30, 31, 33, 33 Build Tools: 28.0.3, 29.0.2, 30.0.2, 30.0.3, 31.0.0, 33.0.0, 33.0.2 System Images: android-24 | Google APIs ARM 64 v8a, android-26 | Google APIs ARM 64 v8a, android-29 | Google APIs ARM 64 v8a, android-31 | Google APIs ARM 64 v8a Android NDK: Not Found IDEs: Android Studio: 2022.1 AI-221.6008.13.2211.9619390 Xcode: 14.3/14E222b - /usr/bin/xcodebuild Languages: Java: 11.0.19 - /usr/bin/javac npmPackages: @react-native-community/cli: Not Found react: 18.2.0 => 18.2.0 react-native: 0.71.8 => 0.71.8 react-native-macos: Not Found npmGlobalPackages: react-native: Not Found

Steps to reproduce

when apps run at android < 10, fetch will show error typeerror

Snack, code example, screenshot, or link to a repository

build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext {
        buildToolsVersion = findProperty('android.buildToolsVersion') ?: '33.0.0'
        minSdkVersion = Integer.parseInt(findProperty('android.minSdkVersion') ?: '21')
        compileSdkVersion = Integer.parseInt(findProperty('android.compileSdkVersion') ?: '33')
        targetSdkVersion = Integer.parseInt(findProperty('android.targetSdkVersion') ?: '33')
        playServicesVersion = "18.0.0"
        androidMapsUtilsVersion = "2.3.0"
        kotlinVersion = "1.6.0"
        frescoVersion = findProperty('expo.frescoVersion') ?: '2.5.0'

    }
    repositories {
        google()
        mavenCentral()
        jcenter()
    }
    dependencies {
        classpath('com.android.tools.build:gradle:7.4.1')
        classpath('com.facebook.react:react-native-gradle-plugin')
        classpath 'com.google.gms:google-services:4.3.15'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

def REACT_NATIVE_VERSION = new File(['node', '--print',"JSON.parse(require('fs').readFileSync(require.resolve('react-native/package.json'), 'utf-8')).version"].execute(null, rootDir).text.trim())

allprojects {
    configurations.all {
        resolutionStrategy {
            force "com.facebook.react:react-native:" + REACT_NATIVE_VERSION
        }
    }
    repositories {
        mavenLocal()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url(new File(["node", "--print", "require.resolve('react-native/package.json')"].execute().text.trim(), "../android"))
        }
        maven {
            // Android JSC is installed from npm
            url(new File(["node", "--print", "require.resolve('jsc-android/package.json')"].execute().text.trim(), "../dist"))
        }

        google()
        mavenCentral()
        jcenter()
        maven { url 'https://www.jitpack.io' }
    }
}

app/build.gradle

apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'
apply plugin: "com.android.application"
apply plugin: "com.facebook.react"
apply plugin: 'com.google.gms.google-services'

import com.android.build.OutputFile

/**
 * This is the configuration block to customize your React Native Android app.
 * By default you don't need to apply any configuration, just uncomment the lines you need.
 */
react {

    /* Folders */
    //   The root of your project, i.e. where "package.json" lives. Default is '..'
    // root = file("../")
    //   The folder where the react-native NPM package is. Default is ../node_modules/react-native
    // reactNativeDir = file("../node_modules/react-native")
    //   The folder where the react-native Codegen package is. Default is ../node_modules/react-native-codegen
    // codegenDir = file("../node_modules/react-native-codegen")
    //   The cli.js file which is the React Native CLI entrypoint. Default is ../node_modules/react-native/cli.js
    // cliFile = file("../node_modules/react-native/cli.js")

    /* Variants */
    //   The list of variants to that are debuggable. For those we're going to
    //   skip the bundling of the JS bundle and the assets. By default is just 'debug'.
    //   If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants.
    // debuggableVariants = ["liteDebug", "prodDebug"]

    /* Bundling */
    //   A list containing the node command and its flags. Default is just 'node'.
    // nodeExecutableAndArgs = ["node"]
    //
    //   The command to run when bundling. By default is 'bundle'
    // bundleCommand = "ram-bundle"
    //
    //   The path to the CLI configuration file. Default is empty.
    // bundleConfig = file(../rn-cli.config.js)
    //
    //   The name of the generated asset file containing your JS bundle
    // bundleAssetName = "MyApplication.android.bundle"
    //
    //   The entry file for bundle generation. Default is 'index.android.js' or 'index.js'
    // entryFile = file("../js/MyApplication.android.js")
    //
    //   A list of extra flags to pass to the 'bundle' commands.
    //   See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle
    // extraPackagerArgs = []

    /* Hermes Commands */
    //   The hermes compiler command to run. By default it is 'hermesc'
    // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc"
    //
    //   The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map"
    // hermesFlags = ["-O", "-output-source-map"]
}

// Override `hermesEnabled` by `expo.jsEngine`
ext {
  hermesEnabled = (findProperty('expo.jsEngine') ?: "hermes") == "hermes"
}

/**
 * Set this to true to create four separate APKs instead of one,
 * one for each native architecture. This is useful if you don't
 * use App Bundles (https://developer.android.com/guide/app-bundle/)
 * and want to have separate APKs to upload to the Play Store.
 */
def enableSeparateBuildPerCPUArchitecture = false

/**
 * Set this to true to Run Proguard on Release builds to minify the Java bytecode.
 */
def enableProguardInReleaseBuilds = false

/**
 * The preferred build flavor of JavaScriptCore (JSC)
 *
 * For example, to use the international variant, you can use:
 * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
 *
 * The international variant includes ICU i18n library and necessary data
 * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
 * give correct results when using with locales other than en-US. Note that
 * this variant is about 6MiB larger per architecture than default.
 */
def jscFlavor = 'org.webkit:android-jsc:+'

/**
 * Private function to get the list of Native Architectures you want to build.
 * This reads the value from reactNativeArchitectures in your gradle.properties
 * file and works together with the --active-arch-only flag of react-native run-android.
 */
def reactNativeArchitectures() {
    def value = project.getProperties().get("reactNativeArchitectures")
    return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
}

buildscript {
    repositories {
        gradlePluginPortal()
    }
    dependencies {
        classpath 'gradle.plugin.com.onesignal:onesignal-gradle-plugin:[0.12.10, 0.99.99]'
    }
}

android {
    compileSdkVersion rootProject.ext.compileSdkVersion

    namespace "com.petskita.petskita"

    defaultConfig {
        applicationId 'com.petskita.petskita'
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 81
        versionName "2.1.78"
        multiDexEnabled true
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include (*reactNativeArchitectures())
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
        release {
            if (project.hasProperty('PETSKITA_UPLOAD_STORE_FILE')) {
                storeFile file(PETSKITA_UPLOAD_STORE_FILE)
                storePassword PETSKITA_UPLOAD_STORE_PASSWORD
                keyAlias PETSKITA_UPLOAD_KEY_ALIAS
                keyPassword PETSKITA_UPLOAD_KEY_PASSWORD
            }
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://reactnative.dev/docs/signed-apk-android.
            signingConfig signingConfigs.release
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }

    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // https://developer.android.com/studio/build/configure-apk-splits.html
            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }

        }
    }

    packagingOptions {
        pickFirst 'lib/x86/libc++_shared.so'
        pickFirst 'lib/x86_64/libjsc.so'
        pickFirst 'lib/arm64-v8a/libjsc.so'
        pickFirst 'lib/arm64-v8a/libc++_shared.so'
        pickFirst 'lib/x86_64/libc++_shared.so'
        pickFirst 'lib/armeabi-v7a/libc++_shared.so'
    }
}

dependencies {
    implementation platform('com.google.firebase:firebase-bom:31.5.0')
    implementation 'com.google.firebase:firebase-auth'

    implementation 'androidx.work:work-runtime-ktx:2.7.1'

    implementation 'androidx.multidex:multidex:2.0.1'

    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'com.google.android.gms:play-services-base:18.2.0'
    implementation 'com.google.android.gms:play-services-location:21.0.1'
    implementation 'com.google.android.gms:play-services-maps:18.1.0'

    implementation "androidx.browser:browser:1.5.0"
    // The version of react-native is set by the React Native Gradle Plugin
    implementation("com.facebook.react:react-android")

    def isGifEnabled = (findProperty('expo.gif.enabled') ?: "") == "true";
    def isWebpEnabled = (findProperty('expo.webp.enabled') ?: "") == "true";
    def isWebpAnimatedEnabled = (findProperty('expo.webp.animated') ?: "") == "true";
    def frescoVersion = rootProject.ext.frescoVersion

    // If your app supports Android versions before Ice Cream Sandwich (API level 14)
    if (isGifEnabled || isWebpEnabled) {
        implementation("com.facebook.fresco:fresco:${frescoVersion}")
        implementation("com.facebook.fresco:imagepipeline-okhttp3:${frescoVersion}")
    }

    if (isGifEnabled) {
        // For animated gif support
        implementation("com.facebook.fresco:animated-gif:${frescoVersion}")
    }

    if (isWebpEnabled) {
        // For webp support
        implementation("com.facebook.fresco:webpsupport:${frescoVersion}")
        if (isWebpAnimatedEnabled) {
            // Animated webp support
            implementation("com.facebook.fresco:animated-webp:${frescoVersion}")
        }
    }

    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
      exclude group:'com.facebook.fbjni'
    }
    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
        exclude group:'com.squareup.okhttp3', module:'okhttp'
    }
    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
    }

    if (hermesEnabled.toBoolean()) {
        implementation("com.facebook.react:hermes-android")
    } else {
        implementation jscFlavor
    }
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.implementation
    into 'libs'
}

apply from: new File(["node", "--print", "require.resolve('@react-native-community/cli-platform-android/package.json')"].execute().text.trim(), "../native_modules.gradle");
applyNativeModulesAppBuildGradle(project)
apply plugin: 'com.google.gms.google-services'

def isNewArchitectureEnabled() {
    // To opt-in for the New Architecture, you can either:
    // - Set `newArchEnabled` to true inside the `gradle.properties` file
    // - Invoke gradle with `-newArchEnabled=true`
    // - Set an environment variable `ORG_GRADLE_PROJECT_newArchEnabled=true`
    return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true"
}

package.json

{
  "overrides": {
    "@types/react": "^18.0.0"
  },
  "scripts": {
    "dev:android": "expo run:android",
    "prod:android": "expo run:android --variant release",
    "dev:ios": "expo run:ios",
    "prod:ios": "expo run:ios --device \"iPhone 14 Pro Max\" --configuration Release",
    "web": "expo start --web",
    "start": "expo start --dev-client",
    "predev:android": "patch-package",
    "test": "echo app packages test scripts",
    "ts-check": "tsc --noEmit",
    "postinstall": "patch-package"
  },
  "resolutions": {
    "@expo/config-plugins": "~6.0.0",
    "@expo/prebuild-config": "~6.0.0",
    "@types/react": "^18.0.29"
  },
  "dependencies": {
    "@expo/config-plugins": "~6.0.0",
    "@gorhom/bottom-sheet": "4.1.5",
    "@react-native-async-storage/async-storage": "1.17.11",
    "@react-native-community/checkbox": "^0.5.8",
    "@react-native-community/clipboard": "^1.5.1",
    "@react-native-community/masked-view": "^0.1.10",
    "@react-native-community/netinfo": "^9.3.10",
    "@react-native-firebase/analytics": "17.5.0",
    "@react-native-firebase/app": "17.5.0",
    "@react-native-firebase/auth": "17.5.0",
    "@react-native-firebase/dynamic-links": "17.5.0",
    "@react-native-firebase/messaging": "17.5.0",
    "@react-navigation/bottom-tabs": "^6.0.5",
    "@react-navigation/material-top-tabs": "^6.0.2",
    "@react-navigation/native": "^6.0.2",
    "@react-navigation/stack": "^6.0.6",
    "@rematch/core": "^1.4.0",
    "@rematch/loading": "^1.2.1",
    "@rematch/persist": "^1.1.0",
    "@sentry/react-native": "^4.15.0",
    "@shopify/flash-list": "1.4.0",
    "class-transformer": "0.4.0",
    "color": "^3.1.3",
    "date-fns": "^2.19.0",
    "date-fns-timezone": "^0.1.4",
    "deprecated-react-native-prop-types": "^4.1.0",
    "expo": "^48.0.0",
    "expo-asset": "~8.9.1",
    "expo-constants": "~14.2.1",
    "expo-dev-client": "~2.2.1",
    "expo-font": "~11.1.1",
    "expo-secure-store": "~12.1.1",
    "expo-splash-screen": "~0.18.2",
    "expo-status-bar": "~1.4.4",
    "expo-updates": "~0.16.4",
    "fbjs": "^3.0.4",
    "formik": "2.2.6",
    "humps": "^2.0.1",
    "i18next": "^20.4.0",
    "immer": "^9.0.2",
    "ky": "0.30.0",
    "lodash.debounce": "^4.0.8",
    "lottie-ios": "3.4.0",
    "lottie-react-native": "5.1.4",
    "numeral": "^2.0.6",
    "qs": "^6.10.1",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-i18next": "^11.11.4",
    "react-native": "0.71.8",
    "react-native-alphabet-sectionlist": "^0.0.4",
    "react-native-android-open-settings": "^1.3.0",
    "react-native-blob-util": "^0.14.0",
    "react-native-collapsible": "^1.6.0",
    "react-native-collapsible-tab-view": "^6.1.4",
    "react-native-confirmation-code-field": "6",
    "react-native-date-picker": "^4.0.0",
    "react-native-device-info": "^8.0.7",
    "react-native-dropdownalert": "^4.3.0",
    "react-native-fast-image": "^8.6.3",
    "react-native-fbsdk-next": "^6.0.0",
    "react-native-freshchat-sdk": "^4.0.2",
    "react-native-geolocation-service": "^5.3.0-beta.3",
    "react-native-gesture-handler": "~2.9.0",
    "react-native-google-places-autocomplete": "^2.4.1",
    "react-native-image-picker": "^5.3.1",
    "react-native-image-viewing": "^0.2.2",
    "react-native-linear-gradient": "^2.5.6",
    "react-native-loading-spinner-overlay": "^2.0.0",
    "react-native-localize": "^2.1.1",
    "react-native-maps": "1.3.2",
    "react-native-masked-text": "^1.13.0",
    "react-native-modal-overlay": "^1.3.1",
    "react-native-notifications": "^4.2.4",
    "react-native-onesignal": "4.3.7",
    "react-native-pager-view": "6.1.2",
    "react-native-pdf": "^6.4.0",
    "react-native-permissions": "^3.2.0",
    "react-native-platform-touchable": "^1.1.1",
    "react-native-reanimated": "~2.14.4",
    "react-native-render-html": "^6.3.1",
    "react-native-safe-area-context": "4.5.0",
    "react-native-screens": "~3.20.0",
    "react-native-section-alphabet-list": "^2.1.0",
    "react-native-share": "^7.6.2",
    "react-native-snap-carousel": "^3.9.1",
    "react-native-svg": "13.4.0",
    "react-native-tab-view": "^3.1.1",
    "react-native-timeline-flatlist": "^0.7.6",
    "react-native-toast-message": "^1.6.0",
    "react-native-vector-icons": "^8.1.0",
    "react-native-web": "~0.18.10",
    "react-native-webview": "11.26.0",
    "react-native-xendit-payment": "^0.5.2",
    "react-query": "^3.39.3",
    "react-redux": "^7.2.5",
    "redux": "^4.1.0",
    "reflect-metadata": "^0.1.13",
    "reselect": "^4.0.0",
    "toggle-switch-react-native": "^3.2.0",
    "ts-deepmerge": "^1.1.0",
    "use-debounce": "^6.0.1",
    "yup": "^0.32.9"
  },
  "devDependencies": {
    "@babel/core": "^7.20.0",
    "@babel/plugin-proposal-decorators": "^7.15.4",
    "@babel/preset-env": "^7.20.0",
    "@babel/runtime": "^7.20.0",
    "@react-native-community/eslint-config": "^3.2.0",
    "@trivago/prettier-plugin-sort-imports": "^4.1.1",
    "@tsconfig/react-native": "^2.0.2",
    "@types/react": "~18.0.27",
    "@types/react-dom": "~18.0.10",
    "@types/react-native": "^0.71.5",
    "@types/react-native-snap-carousel": "^3.8.4",
    "babel-jest": "^29.2.1",
    "babel-plugin-module-resolver": "^5.0.0",
    "babel-plugin-transform-typescript-metadata": "^0.3.2",
    "eslint": "^8.19.0",
    "eslint-config-prettier": "^8.1.0",
    "eslint-plugin-import": "^2.27.5",
    "eslint-plugin-import-order-alphabetical": "^1.0.1",
    "eslint-plugin-react-native-a11y": "^3.3.0",
    "jest": "^29.2.1",
    "metro-react-native-babel-preset": "0.73.9",
    "patch-package": "^6.4.7",
    "pod-install": "^0.1.38",
    "postinstall-postinstall": "^2.1.0",
    "prettier": "^2.4.1",
    "react-native-dotenv": "^3.2.0",
    "react-test-renderer": "18.2.0",
    "typescript": "^4.9.4"
  },
  "jest": {
    "preset": "react-native"
  },
  "expo": {
    "ios": {
      "modulesPaths": [
        "./node_modules"
      ]
    }
  }
}
github-actions[bot] commented 1 year ago
:warning: Newer Version of React Native is Available!
:information_source: You are on a supported minor version, but it looks like there's a newer patch available - 0.71.11. Please upgrade to the highest patch for your minor or latest and verify if the issue persists (alternatively, create a new project and repro the issue in it). If it does not repro, please let us know so we can close out this issue. This helps us ensure we are looking at issues that still exist in the most recent releases.
ferdylimmm9 commented 1 year ago

i solved the solution with this comment https://stackoverflow.com/a/60116643/15010934

  1. create file CustomClientFactory.java in your package
  2. copy code from comment above
  3. copy import com.facebook.react.modules.network.OkHttpClientProvider; into your MainApplication.java
  4. then
@Override
 public void onCreate() {
   super.onCreate();
   SoLoader.init(this, /* native exopackage */ false);  
   OkHttpClientProvider.setOkHttpClientFactory(new CustomClientFactory()); //add this line.
}