0

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
2
  • Are you running this code in a simulator or in you actual mobile phone? Commented Nov 11, 2021 at 14:45
  • I run it on browser Commented Nov 11, 2021 at 15:08

1 Answer 1

1

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);
    }
  };
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.