Issues with Fetch and Axios in React Native are causing functionality to be limited

For 3 different projects, I have been attempting to get fetch or axios to work without success. I've tried adjusting the android manifest as suggested in some troubleshooting threads, but nothing seems to be working. Whether using await/async, promises, or even a simple example like this one, nothing seems to trigger any response - not even the finally statement is executed.

No errors are returned, no logs are generated, simply nothing happens at all.

Upon further investigation, it appears that the Mac/iOS setup works fine, but there seems to be an issue with Windows/Android configurations.

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow strict-local
 */

import React, {useEffect} from 'react';
import {SafeAreaView, Text} from 'react-native';

const App = () => {
  useEffect(() => {
    console.log('hello');
    fetch('http://jsonplaceholder.typicode.com/albums')
      .then(response => {
        console.log('Hello');
        console.log(response.json());
      })
      .then(json => console.log(json))
      .catch(error => console.error(error))
      .finally(() => console.log('Finally'));
  }, []);

  return (
    <SafeAreaView>
      <Text>Hello</Text>
    </SafeAreaView>
  );
};

export default App;

This is how the package.json file looks:

{
  "name": "test",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "axios": "^0.21.1",
    "react": "17.0.1",
    "react-native": "0.64.1"
  },
  "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.14.0",
    "jest": "^26.6.3",
    "metro-react-native-babel-preset": "^0.64.0",
    "react-test-renderer": "17.0.1"
  },
  "jest": {
    "preset": "react-native"
  }
}

Answer №1

The issue stemmed from utilizing http instead of https, resulting in a fetch failure.

There are two ways to structure your API call:

Standard Fetch Method

const NORMAL_FETCH = () => {
  fetch('https://jsonplaceholder.typicode.com/albums')
    .then((response) => {
      return response.json();
    })
    .then((json) => console.log(json))
    .catch((error) => console.error(error))
    .finally(() => console.log('Finally'));
};

Async/Await Approach (my personal preference)

const API_CALL_ASYNC_AWAIT = async () => {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/albums');
    const jsonResponse = await response.json();
    console.log(jsonResponse);
  } catch (error) {
    console.log(error);
  }
};

See the live demo here

Revise your code to this updated version:

import React, { useEffect } from 'react';
import { SafeAreaView, Text } from 'react-native';

const App = () => {
  useEffect(() => {
    API_CALL_ASYNC_AWAIT();
    NORMAL_FETCH();
  }, []);

  const API_CALL_ASYNC_AWAIT = async () => {
    try {
      const response = await fetch(
        'https://jsonplaceholder.typicode.com/albums'
      );
      const jsonResponse = await response.json();
      console.log(jsonResponse);
    } catch (error) {
      console.log(error);
    }
  };

  const NORMAL_FETCH = () => {
    fetch('https://jsonplaceholder.typicode.com/albums')
      .then((response) => {
        return response.json();
      })
      .then((json) => console.log(json))
      .catch((error) => console.error(error))
      .finally(() => console.log('Finally'));
  };

  return (
    <SafeAreaView>
      <Text>Hola</Text>
    </SafeAreaView>
  );
};

export default App;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting CSS Animation Failure in Internet Explorer 11

My mouse over / mouse out animation works perfectly in Firefox and Chrome, but it's not functioning in IE. Can anyone suggest why this might be happening when it was working fine before? var actual = 1; var over = 0; var over2 = 0; function scrol ...

Discovering the index of an item in Angular

My delete function emits socket.io to update the other party's items list and remove the specific item. The issue arises when I receive the socket data as I struggle to find the matching item to update it. Logic User 1 deletes a message User 2 receiv ...

In PHP forms, ensure that only completed textboxes are submitted and empty textboxes are discarded

I've created a form that displays all available products from a database along with their prices. Users can input the quantity they want to purchase for each product, and upon submission, the total amount will be calculated. There are 5 products in th ...

Error in AngularJS when attempting to add a new field within a for loop

I encountered an issue while attempting to add a new "field" into an array. It seems to stop at a specific number of objects within the array. For example, if my array contains 33 objects, the addition stops at the 7th object. This is a snippet of my Java ...

Encountering "No overload matches this call" error in Typescript while working with fetched data and material-ui

Before attempting to create a dropdown menu with an array retrieved using useSWR, I first practiced creating one with a hardcoded array. I used this for the initial practice: https://codesandbox.io/s/76k0ft?file=/demo.tsx:1819-2045 Instead of using a hard ...

Refresh the primary component

I am trying to figure out how to refresh the data in the main component (Parent component) from a child component. In the main component's useEffect, it checks for stored data on the device to determine if the user is registered and their client type. ...

Is there a way to make a React Component to update and navigate to a specific position using react-sound

Currently, I am in the process of constructing an audio player utilizing react-sound. One feature I aim to incorporate is the ability to return to a specific position within the audio track. At the moment, this is my approach: goToVeryCustomPosition() { ...

What is the best method for testing routes implemented with the application router in NextJS? My go-to testing tool for this is vitest

Is it possible to test routes with vitest on Next.js version 14.1.0? I have been unable to find any information on this topic. I am looking for suggestions on how to implement these tests in my project, similar to the way I did with Jest and React Router ...

Error in Next.js: .env variable not defined

I recently transitioned my project from React to Next.js and encountered an issue where my environment variables are showing as undefined, even though they were functioning correctly in React. Can someone provide some guidance or assistance with this probl ...

What advantages does using a watcher provide over a computed property for handling asynchronous tasks or resource-intensive operations in Vue.js?

According to the documentation for Vue.js, utilizing the watch option allows for the execution of asynchronous operations (such as accessing an API), controlling the frequency of these operations, and managing intermediate states leading up to a final outc ...

Deactivate preset styles in react-select library

Is there a way to customize react-select styles? I am having issues with the positioning of react-select within its container, and I currently have to resort to using margin-bottom, which isn't an ideal solution. Here is how it looks without margin-bo ...

Creating an HTML table from a JSON file: Step-by-step guide

I am trying to create a code snippet that populates a table with data from specified .json files in the 'tracks' folder. The JSON file format looks like this: { "EndTime": "11:00", "Person": [ { ...

Is there a way to prevent Prettier on VS Code from automatically unfolding my code blocks when saving?

I have Prettier set up in my VS Code editor with the formatOnSave feature enabled. However, I am facing an issue where every time I save my (js) or (jsx) file, Prettier automatically expands all my functions. Is there a way to stop this from happening? I ...

Can more than one label be assigned to a single bar in a Google column chart?

Is it feasible to include an extra label on every column chart bar without affecting the appearance of the bar itself? This is how my current chart is arranged: this.populationChart.myChartObject.data = { 'cols': [ { id: 's&apo ...

Eliminate any line breaks from the information retrieved from the node event process.stdin.on("data") function

I've been struggling to find a solution to this issue. No matter what approach I take, I can't seem to remove the new line character at the end of my string. Take a look at my code below. I attempted using str.replace() in an effort to eliminate ...

node.js is reporting that it cannot locate some of the modules

Attempting to execute a file using node run index.js within the flashloan test folder results in an error that keeps occurring... node:internal/modules/cjs/loader:1042 throw err; ^ Error: Cannot find module '/home/schette/Documents/flashloan test ...

Navigating using Javascript library in Angular 2 framework

I am currently utilizing Parse, an external JS library, within Angular JS 2. Nevertheless, I am encountering issues when attempting to call the function gotoMain() from within a callback function of Parse. It appears that certain elements are not being l ...

Having trouble getting Node.js, express, socket.io, and ejs to work together?

Currently, I am working on improving my knowledge of java-script and had the idea to create a basic chat app using Express, stock.io, and ejs. Unfortunately, I am facing some challenges in getting it up and running smoothly. Below is the snippet from my ...

Conditional generic type in return type with Typescript

How can I condition the generic return type when a value is not present? type Foo = {}; class Bar<P extends Foo> { static make<P extends Foo>(a?: P): Bar<P> { return new Bar(); } } Bar.make() // returns Bar<Foo> ...

Issues arising from Ionic's functionalities when separated controllers are implemented, resulting in

I utilized the yeoman generator to create an Ionic app. After starting the app with grunt serve, I added a new controller called settings. Index.html: <script src="scripts/controllers/settings.js"></script> Settings js: 'use strict&apo ...