最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - Fetch does not get response from API - Stack Overflow

programmeradmin2浏览0评论

I am building a react-native app and I am new to React Native. While I am a seasoned developer, I do not know much about react-native. At some point, this was working, but then it stopped. I must have changed something system-wide that prevents ALL my API calls from working.

My app makes calls to a Laravel API running on the same machine, and the API is being reached as I see the calls on the console. I have tested my API with Postman and it is returning the correct values. I don't think there is an issue with the API.

The offending app behavior is that it makes the call to the endpoint (reaching it) but does not seem to be catching the API's response, then the app proceeds to die with no errors.

I created a test file that calls a test endpoint that returns a JSON response of "test". This is what the react code looks like:

import React, {useState} from 'react';
import { View, Text } from 'react-native';
import {getBackEndDomain} from "../utilities/utilities";

const Test = async () => {
    const [data, setData] = useState('');
            try {
            const domain = getBackEndDomain();
            console.log(domain); // This prints
            const response = await fetch(domain + '/api/test', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                },
            });
            console.log('test!'); // this does not print

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            setData(data);
            console.log(data);  // Example: Process the returned data
        } catch (error) {
            console.error('Error fetching data:', error);
        }
    return (
        <View>
            <Text>{domain}</Text>
        </View>
    );
};

export default Test;

My main issue is that the fetch is failing and the app stops.

This happens from the Android simulator, the IOS simulator, and from My phone via Expo. The code posted is one of the many versions I have tried, but the issue seems to be somewhere else. Please help me get my sanity back. :)

I am building a react-native app and I am new to React Native. While I am a seasoned developer, I do not know much about react-native. At some point, this was working, but then it stopped. I must have changed something system-wide that prevents ALL my API calls from working.

My app makes calls to a Laravel API running on the same machine, and the API is being reached as I see the calls on the console. I have tested my API with Postman and it is returning the correct values. I don't think there is an issue with the API.

The offending app behavior is that it makes the call to the endpoint (reaching it) but does not seem to be catching the API's response, then the app proceeds to die with no errors.

I created a test file that calls a test endpoint that returns a JSON response of "test". This is what the react code looks like:

import React, {useState} from 'react';
import { View, Text } from 'react-native';
import {getBackEndDomain} from "../utilities/utilities";

const Test = async () => {
    const [data, setData] = useState('');
            try {
            const domain = getBackEndDomain();
            console.log(domain); // This prints
            const response = await fetch(domain + '/api/test', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                },
            });
            console.log('test!'); // this does not print

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            setData(data);
            console.log(data);  // Example: Process the returned data
        } catch (error) {
            console.error('Error fetching data:', error);
        }
    return (
        <View>
            <Text>{domain}</Text>
        </View>
    );
};

export default Test;

My main issue is that the fetch is failing and the app stops.

This happens from the Android simulator, the IOS simulator, and from My phone via Expo. The code posted is one of the many versions I have tried, but the issue seems to be somewhere else. Please help me get my sanity back. :)

Share Improve this question edited 14 hours ago DarkBee 15.6k8 gold badges70 silver badges115 bronze badges asked yesterday user1765388user1765388 13 bronze badges 2
  • You say you're seasoned but I assume you don't have much experience in React? You can't call await in the body of a React component and a component can't be async. You make fetch requests in a useEffect hook. There is an exception to this on the web if it is a RSC (React Server Component) but that's the general rule. – nanobar Commented yesterday
  • 1 Right, I said I was new to React. I also mentioned that I tried a few things. This example is the last thing I tried which was a copy and paste from a website. Thanks for your reply, I will correct the code with your suggestions and try again. – user1765388 Commented yesterday
Add a comment  | 

1 Answer 1

Reset to default 3

The issue with your code is that you are declaring your component function as an async function. React functional components should be synchronous because they must return React elements - not a Promise. Instead, you should perform your asynchronous operation inside a side-effect hook (e.g., useEffect).

const Test = () => {
  const [data, setData] = useState('');
  const domain = getBackEndDomain();

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(`${domain}/api/test`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
          },
        });

        const jsonData = await response.json();
        setData(jsonData);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, [domain]);

  return (
   ...
  );
};
发布评论

评论列表(0)

  1. 暂无评论