Home > OS >  Problem with fetching data to React Native application from express server
Problem with fetching data to React Native application from express server

Time:11-12

I'm trying to develop an android application that fetches data from a local server, although I'm not encountering any errors, I'm not getting the requested data. As the title says I'm using React-Native for my frontend application and Nodejs(expressjs) for backend.

( When I make a get request with cURL, it fetches the data successfully. I run the application on browser )

My server code is this :

const express = require('express')
const cors = require('cors')

const app = express()

app.use(cors())

app.get('/' , async (req, res) => {

    res.send({"abc" : 123})
});

const PORT = process.env.PORT || 5000 

app.listen(PORT, () => console.log(`server started on port ${PORT}`));

My front-end code is this :

import React, { useEffect, useState } from 'react';
import { ActivityIndicator, Text, View } from 'react-native';

const Sandbox = () => {
  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState([]);

  const getData = async () => {
     try {
      const response = await fetch('http://localhost:5000/');
      setData(response);
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    getData();
  }, []);

  return (
    <View style={{ flex: 1, padding: 24 }}>
      {isLoading ? <ActivityIndicator/> : (
        <Text>{Object.keys(data)}</Text>
      )}
    </View>
  );
};

export default Sandbox

CodePudding user response:

Try this:

  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState();

  const fetchData = async (url) => {
    const response = await fetch(url);
    return response.json();
  };

  const getData = () => {
    try {
      fetchData("http://localhost:5000/").then((data) => {
        setData(data);
        setLoading(false);
      });
    } catch (error) {
      console.error(error);
    }
  };
  • Related