I'm trying to fetch data from an API(I created my own Rest API using JSON-server). But I'm unable to fetch anything. however, I'm able to see the data when I navigate to localhost:3000/events. There's no other error in my app. I only get this when I run the app it says network request failed. All the components are working fine. Just not getting the data. I've tried some other online APIs still not getting any response. I've tried with async/await. I'm using the app with IOS but have tried with Andriod as well. Same problem occurs. Attaching the code snippets. Any help would be highly appreciated. Thanks
Created the getEvent Function:
const { manifest } = Constants;
const api = manifest.packagerOpts.dev
? manifest.debuggerHost.split(`:`).shift().concat(`:3000`)
: `api.example.com`;
const url = `http://${api}/events`;
export function getEvents() {
return fetch(url)
.then(response => response.json())
.then(events => events.map(e => ({ ...e, date: new Date(e.date) })))
}
Using it inside the componentDidMount
componentDidMount() {
// getEvents().then(events => this.setState({ events }));
setInterval(() => {
this.setState({
events: this.state.events.map(evt => ({
...evt,
timer: Date.now()
}))
});
}, 1000);
this.props.navigation.addListener("didFocus", () => {
getEvents().then(events => this.setState({ events }));
});
}
Data that I'm trying to fetch.
{
"events": [
{
"title": "Demo a new app",
"date": "2020-03-29T13:45:18.000Z",
"id": "001c9b6d-00a9-465c-a2d3-afb7176a0a87"
}
]
}