I’m facing an issue with fetching data from a server in my React Native project. I’ve been using the Fetch API to make a simple GET request, but I’m unable to retrieve the data. Here’s a snippet of my code:
import React, { useEffect } from 'react';
export default function MyComponent() {
useEffect(() => {
fetchData();
}, []);
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log('Data:', data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
return (
// My component JSX here
);
}
I’ve confirmed that the API endpoint is accessible and returns valid JSON when accessed through a browser or tools like Postman. However, when I run this code in my React Native app, the data
variable remains undefined, and I don’t see any errors in the console.
Could someone please review my code and suggest potential reasons why the Fetch API might not be working as expected in a React Native environment? Any guidance or troubleshooting tips would be greatly appreciated. Thank you!
2
Answers
try adding the header info: