-1

I want to fetch API from my 'https://localhost:7262/api' address, but that is giving Network Error. I want to do GET request and then i am going to do POST request. Also my API server is always open during work.

What Are Your Recommendations?

I created this API using .Net Core 7

Actually, I don't know where this error is, so I felt the need to share the code blocks with you.

Products.js

import React from 'react';
import {SafeAreaView, Text, FlatList, View} from 'react-native';
import ProductCard from '../../components/ProductCard/ProductCard';
import styles from '../Products/Products.style';
import getProducts from '../../fetchApi';
import useFetch from '../../fetchApi';
import Config from 'react-native-config';

const Products = () => {

  const products = useFetch(`${Config.BASE_URL}/Products`);

  const renderProduct = ({item}) => {
    <ProductCard product={item} />;
  };

  return <FlatList data={products} renderItem={renderProduct} />;
};

export default Products;

As you can see i want to show my all data in FlatList method

ProductCard.js

import React, {useEffect, useState} from 'react';
import {View, Text, TouchableWithoutFeedback} from 'react-native';
import styles from './ProductCard.style';

const ProductCard = ({product}) => {
  return (
    <TouchableWithoutFeedback>
      <View style={styles.container}>
        <Text style={styles.text}>{product.productName}</Text>
        <Text style={styles.text}>{product.quantity}</Text>
        <Text style={styles.text}>{product.category}</Text>
      </View>
    </TouchableWithoutFeedback>
  );
};
export default ProductCard;

I have three pieces of data that I need to fetch and show.

fetchApi.js

import {useEffect, useState} from 'react';
import axios from 'axios';

function useFetch(url) {
  const [products, setProducts] = useState([]);

  //const BASE_URL = 'https://localhost:7262/api'; //I don't use that, i use this address from .env file

  const getProducts = async () => {
    try {
      const {products: responseProducts} = await axios.get(url);
      setProducts(responseProducts);
    } catch (error) {
      console.error(error);
    }
  };

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

  return {products};
}

export default useFetch;

This is fetchApi file, my all axios codes is here.

.env

BASE_URL = https://localhost:7262/api/

I get URL from environment file as you can see, if you have other solution you can tell me and i can change that.

Package.json

{
  "name": "apidotnet",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "ios-dev": "react-native run-ios --scheme \"apidotnetDev\"",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@react-navigation/native": "^6.1.4",
    "@react-navigation/native-stack": "^6.9.10",
    "axios": "^1.3.3",
    "https": "^1.0.0",
    "react": "17.0.2",
    "react-native": "0.68.2",
    "react-native-config": "^1.5.0",
    "react-native-safe-area-context": "^4.5.0",
    "react-native-screens": "^3.20.0"
  },
  "devDependencies": {
    "@babel/core": "^7.20.12",
    "@babel/runtime": "^7.20.13",
    "@react-native-community/eslint-config": "^3.2.0",
    "babel-jest": "^29.4.2",
    "eslint": "^8.34.0",
    "jest": "^29.4.2",
    "metro-react-native-babel-preset": "^0.75.0",
    "react-test-renderer": "17.0.2"
  },
  "jest": {
    "preset": "react-native"
  }
}

Router.js

import * as React from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {createNativeStackNavigator} from '@react-navigation/native-stack';

import Products from './pages/Products';

const Stack = createNativeStackNavigator();

const Router = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen
          name="ProductsPage"
          component={Products}
          options={{
            title: 'Ürünler',
            headerStyle: {backgroundColor: 'green'},
            headerTitleStyle: {color: 'white'},
          }}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
};
export default Router;

.Net File

using System;
using InventoryControl.Models;
using InventoryControl.Services;
using Microsoft.AspNetCore.Mvc;
namespace InventoryControl.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ProductsController : ControllerBase
    {
        private readonly ProductsService _productsService;
        public ProductsController(ProductsService productsService) =>
            _productsService = productsService;
        

        [HttpGet]
        public async Task<List<Products>> Get() => await _productsService.GetProductAsync();

        [HttpPost]
        public async Task <IActionResult> Post(Products newProduct)
        {
            await _productsService.CreateProductAsync(newProduct);
            

            return CreatedAtAction(nameof(Get), new { id = newProduct.Id }, newProduct);
        }


        [HttpGet("{id:length(24)}")]
        public async Task<ActionResult<Products>> Get(string id)
        {
            var product = await _productsService.GetProductAsync(id);

            if(product is null)
            {
                return NotFound();
            }
            return product;
        }
        [HttpPut("{id:length(24)}")]
        public async Task<IActionResult> Update(string id, Products updatedProduct)
        {
            var product = await _productsService.GetProductAsync(id);//first step, we must fetch the data from id

            if(product is null)
            {
                return NotFound();
            }
            updatedProduct.Id = product.Id;

            await _productsService.UpdateProductAsync(id, updatedProduct);
            return NoContent();
        }

        [HttpDelete]
        public async Task<IActionResult> Delete(string id)
        {
            var product = await _productsService.GetProductAsync(id);
            if(product is null)
            {
                return NotFound();
            }
            await _productsService.RemoveProductAsync(id);

            return NoContent();
        }


        
    }
}



2
  • I assume you already tested your api and its working fine on that end right? Commented Feb 20, 2023 at 13:31
  • Yes exactly, it works on Postman and Swagger. I can post or get any data using that api. Commented Feb 20, 2023 at 13:34

2 Answers 2

2

I think there is two problems with your BASE_URL env variable.

  1. Remove the s of http. localhost is most of the time unsecure
  2. Remove the last /
BASE_URL=http://localhost:7262/api

EDIT:

Could try to edit your useFetch hook and share the log to us:

function useFetch(url) {
  const [products, setProducts] = useState([]);

  const getProducts = async () => {
    try {
      axios.interceptors.request.use((request) => {
        console.log(JSON.stringify(request, null, 2)); // <--- this log
        return request;
      });
      
      const {products: responseProducts} = await axios.get(url);
      setProducts(responseProducts);
    } catch (error) {
      console.error(error);
    }
  };

  useEffect(() => {
    getProducts();
  }, []);
Sign up to request clarification or add additional context in comments.

18 Comments

It didn't work.
I did and it gave Network Error again.
Can you remove the last / in your BASE_URI env?
I already did that.
Can you double check and restart your server. If you don't, new env variables won't get live updated
|
0

If you are testing on iOS, make sure you added the desired URL in the App Transport Security settings. Then, run npx react-native run-ios.

1 Comment

It didn't work.

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.