C
C#BearCooder

How to connect my c# backend with the frontend?

Hello, I created a ASP NET Core Web Api project with the command dotnet new webapi -minimal. In my program.cs I am fetching some data from a public server and displaying it in plaintext for now when I run it and open localhost. So it works perfectly but since I am a beginner I have two questions. 1. Is my code and approach fine the way I did it? Is there anything what I can improve? 2. How can I connect this with a React frontend to display the some values from the fetch? I know how to work with react but I am missing the link how to connect each other? I uploaded the code on github here: https://github.com/BearCooder/ASP.NET-Core Basically the code is only in program.cs I appreciate any help!
K
Keswiik45d ago
manually adding a react app to an existing asp.net project can be a bit of a hassle, if you have VS or Rider there should be templates for ASP projects that include react It would probably be easier for you to create a new project (that supports react already) and then copy your existing code over
B
BearCooder45d ago
Ah I did not know this. I use VSCode. I was looking for a best practice how to work with c# and react but at the end I was not sure whats the right approach to be honest
K
Keswiik45d ago
I would personally recommend using a proper IDE instead of VSCode for working with c# but there are probably ways to create templated projects from the CLI
P
Pobiega45d ago
There are, it's a template of its own However you don't need to use that template. It's very common to simply run your react app on its own Set up a dev proxy to redirect your api traffic, and thats all you need
B
BearCooder45d ago
So you mean something like adding a proxy in my package json where my react app e.g. "proxy": "http://localhost:5000"? And using the port where my ASP NET Core app is running.
P
Pobiega44d ago
Yeah, something like that We use vite at work and have that setup It works great
B
BearCooder44d ago
Ok that sounds good I also use Vite with React. And then I should be able to display certain data with axios?
P
Pobiega44d ago
well, axios lets you make requests to the backend, yes then you do react stuff with that data to show it 🙂
A
Angius44d ago
Or you can ditch Axios and just use fetch() ¯\_(ツ)_/¯
B
BearCooder44d ago
Yes true. I just have a problem to make a successfull request to my ASP NET Core app to see the data on the frontend. And I was trying either with axios or fetch. This is what I try in React. The backend code is in my program.cs in the github link. No matter what I try I get TypeErrors in browser console. And now its patient.name.given is undefined.
import React, { useEffect, useState } from 'react';

interface Patient {
id: string;
name: { family: string; given: string[] };
birthDate: string;
identifier: { value: string }[];
}

const DataList: React.FC = () => {
const [patients, setPatients] = useState<Patient[]>([]);

useEffect(() => {
const fetchData = async () => {
const response = await fetch('http://localhost:4000/patient');
const data: { entry: { resource: Patient }[] } = await response.json();
setPatients(data.entry.map((entry) => entry.resource));
};

fetchData();
}, []);

return (
<div>
<h2>Patient List</h2>
<table>
<thead>
<tr>
<th>Id</th>
<th>Given Name</th>
<th>Family Name</th>
<th>Birth Date</th>
<th>Identifier</th>
</tr>
</thead>
<tbody>
{patients.map((patient) => (
<tr key={patient.id}>
<td>{patient.id}</td>
<td>{patient.name.given.join(' ')}</td>
<td>{patient.name.family}</td>
<td>{patient.birthDate}</td>
</tr>
))}
</tbody>
</table>
</div>
);
};

export default DataList;
import React, { useEffect, useState } from 'react';

interface Patient {
id: string;
name: { family: string; given: string[] };
birthDate: string;
identifier: { value: string }[];
}

const DataList: React.FC = () => {
const [patients, setPatients] = useState<Patient[]>([]);

useEffect(() => {
const fetchData = async () => {
const response = await fetch('http://localhost:4000/patient');
const data: { entry: { resource: Patient }[] } = await response.json();
setPatients(data.entry.map((entry) => entry.resource));
};

fetchData();
}, []);

return (
<div>
<h2>Patient List</h2>
<table>
<thead>
<tr>
<th>Id</th>
<th>Given Name</th>
<th>Family Name</th>
<th>Birth Date</th>
<th>Identifier</th>
</tr>
</thead>
<tbody>
{patients.map((patient) => (
<tr key={patient.id}>
<td>{patient.id}</td>
<td>{patient.name.given.join(' ')}</td>
<td>{patient.name.family}</td>
<td>{patient.birthDate}</td>
</tr>
))}
</tbody>
</table>
</div>
);
};

export default DataList;
K
Keswiik44d ago
so log the result you're getting from the fhir api and make sure it contains what you're expecting?
K
Keswiik44d ago
https://github.com/BearCooder/ASP.NET-Core/blob/cacc0433de246c61d75df2d0ca7790aaa007459a/Program.cs#L27 if this is still how you have it written, I would expect things to fail
GitHub
ASP.NET-Core/Program.cs at cacc0433de246c61d75df2d0ca7790aaa007459a...
Contribute to BearCooder/ASP.NET-Core development by creating an account on GitHub.
K
Keswiik44d ago
you aren't returning a valid json object here
Want results from more Discord servers?
Add your server
More Posts
✅ Using `Func<ReadOnlySpan<char>,bool>` but not allowed due to Pointer TypeI am building a parser, and performance is of concern. So instead of allocating infinite strings wheconcurrency and atomicity Asp.net core web api and efcorelet's say there's an endpoint called AssingUser() ,this endpoint assigns one donation to this currenBuilding a generic repository for mongodbhello folks I was thinking build a generic repository structure for mongodb. but someday if i want Reading large xml file from archive by using XmlReader in Parallel modeHello 👋. I am looking for how can I read data from archive xml file in Parallel mode. I have archiResizing the Console window - Console ApplicationHi there, I'm trying to resize the console window in a Console Application. I have tried multiple ✅ Creating a datetime with a timezoneHow do I create a `DateTime` with `new DateTime(2010, 05, 12);` and give it a specific `TimeZoneInfoCustom Newtonsoft JSON deserializationI have a dictionary where: - The key will always be a string - The value will be either: - string Issue with Form.Close() in WinformsI have a custom form called CustomMessageBox In that form, I have a method that defines a button clIssue with IMGUI.Net.Hello, I am creating an ImGUI application and It doesn't let me move the ui across my entire screen,Issue with deserializing Enums in saved JSONHey, I've been trying to deserialize a list of cards I serialized in C#, the issue I'm having is it From HttpClient, can I save/copy the request to share with someone?Is there a way to copy raw request details? For example, I'm looking for a similar output like: -3D Unity RaycastingHi guys, currently working on a puzzle game involving lasers and mirrors, however, have hit a brick Computer Science - Computer ArchitectureOn a 64 bit system (where the bus length and word size are 64 bits) how would we determine the ammouConnecting SQLite in MAUIHow to connect the database without absolute path? If with it, the program works only on the computeDifferent HttpClient headersWhen I make an HTTP request in my browser (Chrome), I get different response headers than I do in myHttpRequestException:An error occurred while sending the request. WebExceptionHttpRequestException:An error occurred while sending the request. WebException:Unable to connect to ✅ EF does not put datetimes properly to the datebaseI am writing a backend app in asp.net core. This is my service code : ```c# public virtual async TaShadow Prop Error with IdentityDbContextThis is my IdentityDbContext: public class ApplicationUser : IdentityUser { [Required(ErrorMessWpf custom button template probleHi! I am trying to create custom button control, but I have a problem with a content property. ButtoWinfoms problem in Hosts fileI am writing a mini site blocker, the program has 2 functions to block the site and add the site tha