0

Am trying to make a simple react native app that fetches the data from my express (nodejs app) and just simply show case it. the app works fine with api links I used from the web but for some reason when I use my own local server ( my own nodejs app) it doesn't show anything.

Am new to react native so I need your help.

This the code of my App.js ( from react native ) :

import React, { Component } from "react";
import { Platform, StyleSheet, Text, View, FlatList } from "react-native";
export default class App extends Component<Props> {
  state = {
    data: [],
  };

  fetchData = async () => {
    const response = await fetch("http://myipadress:5001/articles");
    const articles = await response.json();
    this.setState({ data: articles });
  };
  componentDidMount() {
    this.fetchData();
  }
  render() {
    return (
      <View>
        <Text>data</Text>

        <FlatList
          data={this.state.data}
          keyExtractor={(item, index) => index.toString()}
          renderItem={({ item }) => (
            <View
              style={{ backgroundColor: "#abc123", padding: 10, margin: 10 }}
            >
              <Text style={{ color: "#fff", fontWeight: "bold" }}>
                {item.title}
              </Text>

              <Text>{item.genre}</Text>
            </View>
          )}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#F5FCFF",
  },
});

and this is my api : that i access from the link http://myipadress:5001/articles :

[
    {
        "featured_media": {
            "source_url": "String",
            "caption": "String",
            "media_type": "String"
        },
        "categories": [
            "String"
        ],
        "tags": [
            "String"
        ],
        "_id": "5ea02d3d12d8153e34f779ca",
        "date": "2020-04-22T11:40:45.000Z",
        "title": "String",
        "excerpt": "String",
        "author": "String",
        "link": "String",
        "published_at": "2020-04-22T11:40:45.000Z",
        "content": "String",
        "__v": 0
    }
]
Max
  • 412
  • 5
  • 21

2 Answers2

0

React native doesn't work with the same environment on local machine. You can try this code or axios. But as far as I know it doesn't work in the same local environment.

async () => {
    await fetch('http://myipadress:5001/articles')
    .then((response) => response.json())
    .then((responseJson) => console.log(responseJson))
    .catch(err => console.log(err);

}
Ali Anwar
  • 233
  • 1
  • 4
  • 11
  • the code didn't work but i will check axios out thank you – Max Apr 22 '20 at 13:27
  • Did u use await before this code and called it async – Ali Anwar Apr 23 '20 at 07:09
  • should i use the code like this : fetchData = async () => { const response = await fetch( "https://raw.githubusercontent.com/Hardeepcoder/fake_json/master/Users" ) .then((response) => response.json()) .then((responseJson) => console.log(responseJson)) .catch((err) => console.log(err)); this.setState({ data: response }); }; – Max Apr 23 '20 at 10:34
  • If you are using promises in javascript you can setState in promises where u get the required data link in second .then. Read your console output like .then(responseJson) => setState({...state, data:responseJson})) in case you are using react hooks. – Ali Anwar Apr 23 '20 at 17:34
0

I believe the problem here is that you are trying to fetch from an HTTP endpoint which is your local server here. I used to have this problem when I was developing an app with Expo SDK. You can fix this by installing ngrok which will expose an HTTPS endpoint for your local server.

Download ngrok and run ngrok http 5001or your port number on your terminal. ngrok will expose a HTTPS endpoint which you can use to fetch data.

fetchData = async () => {
    const response = await fetch("replace-with-new-ng-rk-url/articles");
    const articles = await response.json();
    this.setState({ data: articles });
  };
Ajin Kabeer
  • 2,096
  • 2
  • 9
  • 18
  • i exposed the port 5001 and changed the link inside fetch with the ngrok link/articles and for some reason it still returns nothing i also tried the same process for a diffrent server ( a movies api ) and it didnt work either – Max Apr 22 '20 at 14:15
  • can you paste the link you got in the comment here, just to make sure? – Ajin Kabeer Apr 22 '20 at 14:29
  • This is the link i got from exposing the port 5001 using ngrok http 5001 : https://a51b95cd.ngrok.io/articles – Max Apr 22 '20 at 14:37
  • Alright, can you log `articles` after the line `const articles = await response.json();` – Ajin Kabeer Apr 22 '20 at 14:38
  • i get something like Access to fetch at 'https://a51b95cd.ngrok.io/articles' from origin 'https://localhost:19006' 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. – Max Apr 22 '20 at 14:45
  • Can you take a look at the first answer of this [question](https://stackoverflow.com/questions/43262121/trying-to-use-fetch-and-pass-in-mode-no-cors) ? – Ajin Kabeer Apr 22 '20 at 14:50