Reputation: 77
I have a problem fetching JSON data from url. I would really appreciate it if you could help me solve this issue.
I wanted to fetch JSON data from firebase storage, but somewhat I can't, so I simplified the code and now it's really simple, but no luck. I also searched the cause of the error in this community, but I didn't find it.
This is my code.
import React, { Component } from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
export default class App extends Component {
render() {
return (
<View>
<TouchableOpacity onPress={this.handleOnPress}>
<Text>test</Text>
</TouchableOpacity>
</View>
);
}
handleOnPress = () => {
console.log('test was clicked');
fetch('https://facebook.github.io/react-native/movies.json')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
};
}
needless to say, the message, 'test was clicked' is displayed without any problem
Error message
Error: "Failed to fetch" in TypeError: Failed to fetch ...
I use Expo Snack, web compiler.
Thank you.
Upvotes: 0
Views: 1858
Reputation: 9
here is 2 methods that using for async fatching data from json file URL with javascript
using fetch + .then
function loadUsers_then() {
let url = '< Your URL Here>';
try{
fetch(url)
.then((response) => { return response.json() })
.then((data) => {
for (let curr of data.results) {
str += `<Your html string here>`
}
document.querySelector('#mydiv').innerHTML = str;
})
}}
catch(err){
console.log('there was an error', err);
}
using async + await
async function loadusers_async_await() {
let url = '< Your URL Here>';
try {
let response = await fetch(url);
let data = await response.json();
let str = '';
for (let curr of data.results) {
str += `<Your html string here> < ${curr.key1.key2...} >`
}
document.querySelector('#mydiv').innerHTML = str;
}
catch (err) {
console.log('there was an error', err);
}
}
Upvotes: 0
Reputation: 140
Is the error before Failed to fetch:
Access to fetch at 'https://facebook.github.io/react-native/movies.json' from origin 'XXX' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
If so, it is a CORS issue.
If not, feel free to post any other information you are seeing. I'm sure there must be more errors logged than - Failed to Fetch.
Upvotes: 1