Data not being fetched from sql server to Visual Studio Code and not being displayed when executed

Hello,

I was writing a REACT code on Visual Studio and wanted my database files (sql server) to be fetched. But I can’t figure out why it isn’t displaying it when I run the code. Can you please help? Here is the code:

import React,{Component} from 'react';

import {Table} from 'react-bootstrap';

export class Carrent extends Component{

    constructor(props){

        super(props);

        this.state={deps:[]}

    }

refreshList(){

    fetch(process.env.REACT_APP_API+'carrent')

    .then(response=>response.json())

    .then(data=>{

        this.setState({deps:data});

    });

}

componentDidMount(){

    this.refreshList();

}

componentDidUpdate(){

    this.refreshList();

}

    render(){

        const {deps} =this.state;

        return(

            <div >

                <Table ClassName="mt-4" striped bordered hover size="sm">

                    <thead>

                        <tr>

                        <th>OrganizationID</th>

                        <th>OrganizationName</th>

                        <th>BriCarLimousine</th>

                        <th>BriCarSeregela</th>

                        <th>BriCarOldies</th>

                        <th>BriCarMercedes</th>

                        <th>BriCarHammer</th>

                        <th>BMCarLimousine</th>

                        <th>BMCarSmiley</th>

                        <th>BMCarOldies</th>

                        <th>BMCarMercedes</th>

                        <th>BMCarCorolla</th>

                        <th>Budget</th>

                        <th>ServiceQuality</th>

                        <th>ServicePrice</th>

                        <th>Options</th>

                        </tr>

                    </thead>

                    <tbody>

                        {deps.map(dep=>

                            <tr key={dep.OrganizationID}>

                                <td>{dep.OrganizationID}</td>

                                <td>{dep.OrganizationName}</td>

                                <td>{dep.BriCarLimousine}</td>

                                <td>{dep.BriCarSeregela}</td>

                                <td>{dep.BriCarOldies}</td>

                                <td>{dep.BriCarMercedes}</td>

                                <td>{dep.BriCarHammer}</td>

                                <td>{dep.BMCarLimousine}</td>

                                <td>{dep.BMCarSmiley}</td>

                                <td>{dep.BMCarOldies}</td>

                                <td>{dep.BMCarMercedes}</td>

                                <td>{dep.BMCarCorolla}</td>

                                <td>{dep.Budget}</td>

                                <td>{dep.ServiceQuality}</td>

                                <td>{dep.ServicePrice}</td>

                                <td>Edit / Delete</td>

                            </tr>)}

                    </tbody>

                </Table>

            </div>

        )

    }

}

Thanks for your cooperation!

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Are you getting an error message?

Can you put a .catch on your fetch to catch and log the error?

Thanks for that, Kevin. I’ll do that in the future.

No there is no error currently. Where specifically can I add the .catch code? Is only adding .catch enough? I am new to REACT. So please bear with me.

The catch method is part of a Promise. You would use it like:

myPromise()
  .then( /* do what you want */ )
  .catch(err => console.error(err))

If anything in the Promise throws an error, the catch method will catch it, like in a try/catch.

Thanks for responding, Kevin. I have added the following .catch code and rerun (npm start) my code. But it didn’t catch any error:

refreshList(){
    fetch(process.env.REACT_APP_API+'carrent')
    .then(response=>response.json())
    .then(data=>{
        this.setState({deps:data});
    }).catch((error) => {
        console.log(error);
      });
    
}

Then diagnose the problem. We don’t have access to your code and DB so you’re going to have to figure some stuff out for us. I’m assuming that you’re not comfortable with break points, but you can always log things. I would do something like:

refreshList(){
    console.log('entering refreshList')
    const url = process.env.REACT_APP_API+'carrent'
    console.log('fetching url', url)
    fetch(process.env.REACT_APP_API+'carrent')
    .then(
      response=> {
        console.log('first then', response)
        return response.json()
      }
    )
    .then(data=>{
        console.log('second then', data)
        this.setState({deps:data});
    }).catch((error) => {
        console.log(error);
      });
}

I would do that to try and understand where the issue is.

I tried to try and catch in every places of the code. But no error is being caught. I am also doubting if the problem is with my Visual Studio 2022 controller code. Postman shows 404 Not found error. Can you please check it? Here is the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System.Data.SqlClient;
using System.Data;
using TiloshDesetWebApp.Models;
using System.IO;
using Microsoft.AspNetCore.Hosting;

namespace TiloshDesetWebApp.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class CarrentController : ControllerBase
    {
        private readonly IConfiguration _configuration;
        private readonly IWebHostEnvironment _env;

        public CarrentController(IConfiguration configuration, IWebHostEnvironment env)
        {
            _configuration = configuration;
            _env = env;
        }

        [HttpGet]
        public JsonResult Get()
        {
            string query = @"
                    select OrganizationId, OrganizationName, BriCarLimousine,
                    BriCarSeregela, BriCarOldies, BriCarMercedes, BriCarHammer, 
                    BMCarLimousine, BMCarSmiley, BMCarOldies, BMCarMercedes, 
                    BMCarCorolla, Budget, ServiceQuality, ServicePrice
                    from dbo.Carrent
                    ";
            DataTable table = new DataTable();
            string sqlDataSource = _configuration.GetConnectionString("TiloshdesetAppCon");
            SqlDataReader myReader;
            using (SqlConnection myCon = new SqlConnection(sqlDataSource))
            {
                myCon.Open();
                using (SqlCommand myCommand = new SqlCommand(query, myCon))
                {
                    myReader = myCommand.ExecuteReader();
                    table.Load(myReader); ;

                    myReader.Close();
                    myCon.Close();
                }
            }

            return new JsonResult(table);
        }


        [HttpPost]
        public JsonResult Post(CarRent cr)
        {
            string query = @"
                    insert into dbo.Carrent values 
                    ('" + cr.OrganizationName + @"')
                    ";
            DataTable table = new DataTable();
            string sqlDataSource = _configuration.GetConnectionString("TiloshdesetAppCon");
            SqlDataReader myReader;
            using (SqlConnection myCon = new SqlConnection(sqlDataSource))
            {
                myCon.Open();
                using (SqlCommand myCommand = new SqlCommand(query, myCon))
                {
                    myReader = myCommand.ExecuteReader();
                    table.Load(myReader); ;

                    myReader.Close();
                    myCon.Close();
                }
            }

            return new JsonResult("Added Successfully");
        }


        [HttpPut]
        public JsonResult Put(CarRent cr)
        {
            string query = @"
                    update dbo.Carrent set 
                    OrganizationName = '" + cr.OrganizationName + @"'
                    ,BriCarLimousine = '" + cr.BriCarLimousine + @"'
                    ,BriCarSeregela = '" + cr.BriCarSeregela + @"'
                    ,BriCarOldies = '" + cr.BriCarOldies + @"'
                    ,BriCarMercedes = '" + cr.BriCarMercedes + @"'
                    ,BriCarHammer = '" + cr.BriCarHammer + @"'
                    ,BMCarLimousine = '" + cr.BMCarLimousine + @"'
                    ,BMCarSmiley = '" + cr.BMCarSmiley + @"'
                    ,BMCarOldies = '" + cr.BMCarOldies + @"'
                    ,BMCarMercedes = '" + cr.BMCarMercedes + @"'
                    ,BMCarCorolla = '" + cr.BMCarCorolla + @"'
                    ,Budget = '" + cr.Budget + @"'
                    ,ServiceQuality = '" + cr.ServiceQuality + @"'
                    ,ServicePrice = '" + cr.ServicePrice + @"'
                    where OrganizationId = " + cr.OrganizationId + @" 
                    ";
            DataTable table = new DataTable();
            string sqlDataSource = _configuration.GetConnectionString("TiloshdesetAppCon");
            SqlDataReader myReader;
            using (SqlConnection myCon = new SqlConnection(sqlDataSource))
            {
                myCon.Open();
                using (SqlCommand myCommand = new SqlCommand(query, myCon))
                {
                    myReader = myCommand.ExecuteReader();
                    table.Load(myReader); ;

                    myReader.Close();
                    myCon.Close();
                }
            }

            return new JsonResult("Updated Successfully");
        }


        [HttpDelete("{id}")]
        public JsonResult Delete(int id)
        {
            string query = @"
                    delete from dbo.Carrent
                    where OrganizationId = " + id + @" 
                    ";
            DataTable table = new DataTable();
            string sqlDataSource = _configuration.GetConnectionString("TiloshdesetAppCon");
            SqlDataReader myReader;
            using (SqlConnection myCon = new SqlConnection(sqlDataSource))
            {
                myCon.Open();
                using (SqlCommand myCommand = new SqlCommand(query, myCon))
                {
                    myReader = myCommand.ExecuteReader();
                    table.Load(myReader); ;

                    myReader.Close();
                    myCon.Close();
                }
            }

            return new JsonResult("Deleted Successfully");
        }
        [Route("SaveFile")]
        [HttpPost]
        public JsonResult SaveFile()
        {
            try
            {
                var httpRequest = Request.Form;
                var postedFile = httpRequest.Files[0];
                string filename = postedFile.FileName;
                var physicalPath = _env.ContentRootPath + "/Photos/" + filename;

                using (var stream = new FileStream(physicalPath, FileMode.Create))
                {
                    postedFile.CopyTo(stream);
                }

                return new JsonResult(filename);
            }
            catch (Exception)
            {

                return new JsonResult("anonymous.png");
            }
        }


        [Route("GetAllOrganizationNames")]
        public JsonResult GetAllOrganizationNames()
        {
            string query = @"
                    select OrganizationName from dbo.Carrent
                    ";
            DataTable table = new DataTable();
            string sqlDataSource = _configuration.GetConnectionString("TiloshdesetAppCon");
            SqlDataReader myReader;
            using (SqlConnection myCon = new SqlConnection(sqlDataSource))
            {
                myCon.Open();
                using (SqlCommand myCommand = new SqlCommand(query, myCon))
                {
                    myReader = myCommand.ExecuteReader();
                    table.Load(myReader); ;

                    myReader.Close();
                    myCon.Close();
                }
            }

            return new JsonResult(table);
        }


    }
}

That is a language I don’t do. I was trying to help you with React because that is something I do.

But if it is being rejected by your API, then the f/e should still catch an error. I still don’t see what your log output is from what I suggested.

But I you are sure that it is a problem with your server, then I would start a new thread and label it as such. If your server is having difficulty, then you’d have to do the debugging there.

Dear Kevin, I really appreciate your effort to solve this. Can I share you my screen using Team Viewer and check the try and catch we talked about earlier? I am not sure if I implemented what you told me properly. It isn’t catching any error at all. Thanks!

Sorry, I’m not able to do something like that. And I was suggesting to use a catch method, not specifically a try/catch but that could work.

If you are unsure of the code, please post it.

Dear Kevin,
This is the result I get on my DEBUG COSOLE tab:

first then Response {type: 'basic', url: 'http://localhost:3000/undefinedcarrent', redirected: false, status: 200, ok: true, …}

SyntaxError: Unexpected token < in JSON at position 0 {stack: 'SyntaxError: Unexpected token < in JSON at position 0', message: 'Unexpected token < in JSON at position 0'}

Uncaught SyntaxError: Unexpected token < in JSON at position 0

entering refreshList

fetching url undefinedcarrent

first then Response {type: 'basic', url: 'http://localhost:3000/undefinedcarrent', redirected: false, status: 200, ok: true, …}

SyntaxError: Unexpected token < in JSON at position 0 {stack: 'SyntaxError: Unexpected token < in JSON at position 0', message: 'Unexpected token < in JSON at position 0'}

The development server has disconnected. Refresh the page if necessary.

Does that make any sense?

This doesn’t bring anything to mind? That url?