12. Power Up React with .NET API Connections

Lokesh Chaudhari
4 min readMay 23, 2024

--

Integrating a React frontend with a .NET API backend is a common scenario in modern web development. In this blog, we’ll explore how to fetch data from a .NET API in a React application. We’ll discuss the use of Axios and Fetch for making HTTP requests, as well as how to handle asynchronous operations and error handling.

how APIs work

Fetching Data from a .NET API in React

To fetch data from a .NET API in a React application, you’ll typically use the fetch API or a third-party library like Axios . Both methods are viable options, but Axios is often preferred due to its simplicity and additional features.

Using Axios:

  1. Install Axios in your React project:
npm install axios

2. Import Axios and make a GET request to the .NET API endpoint:

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

function App() {
const [data, setData] = useState([]);

useEffect(() => {
axios.get('https://your-dotnet-api.com/api/data')
.then(response => {
setData(response.data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
}, []);

return (
<div>
<h1>Data from .NET API</h1>
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
}

export default App;

Using Fetch:

Alternatively, you can use the built-in fetch API:

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

function App() {
const [data, setData] = useState([]);

useEffect(() => {
fetch('https://your-dotnet-api.com/api/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
setData(data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
}, []);

return (
<div>
<h1>Data from .NET API</h1>
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
}

export default App;

Axios vs Fetch for Making HTTP Requests

Both Axios and Fetch are popular choices for making HTTP requests in JavaScript applications. Here’s a comparison of the two:

Axios:

  • Provides a simple and intuitive API for making HTTP requests.
  • Supports interceptors, which allow you to globally intercept and modify requests and responses.
  • Automatically converts response data to JSON.
  • Has built-in support for handling request and response headers.
  • Supports cancellation of requests.

Fetch:

  • Built-in to modern browsers, so no additional dependencies are required.
  • Uses Promises, making it easy to work with asynchronous code.
  • Provides a low-level API for making requests, allowing for more fine-grained control.
  • Requires manual conversion of response data to JSON.
  • Lacks some features found in Axios, such as interceptors and request cancellation.

Handling Asynchronous Operations and Error Handling

When fetching data from a .NET API in React, it’s essential to handle asynchronous operations and error handling properly. Here are some best practices:

  • Use useEffect: Use the useEffect hook to fetch data when the component mounts.
  • Handle Errors: Use try-catch blocks or .catch() methods to handle errors when fetching data.
  • Display Loading State: Show a loading indicator while the data is being fetched to provide feedback to the user.
  • Handle Empty Data: Check if the data array is empty and display a message if no data is returned from the API.

Demonstration: Fetching Data from a .NET API in React

Let’s create a simple React application that fetches data from a .NET API using Axios.

Step-by-Step Guide:

  1. Set Up React Project: Create a new React project using Create React App:
npx create-react-app my-app
cd my-app

2. Install Axios: Install Axios in your project:

npm install axios

3. Create Component: Create a new component (e.g., DataList.js) and add the following code to fetch data from the .NET API:

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

function DataList() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);

useEffect(() => {
axios.get('https://your-dotnet-api.com/api/data')
.then(response => {
setData(response.data);
setLoading(false);
})
.catch(error => {
console.error('Error fetching data:', error);
setLoading(false);
});
}, []);

if (loading) {
return <div>Loading...</div>;
}

return (
<div>
<h1>Data from .NET API</h1>
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
}

export default DataList;

4. Use Component: Import and use the DataList component in your App.js:

import React from 'react';
import DataList from './DataList';

function App() {
return (
<div>
<DataList />
</div>
);
}

export default App;

5. Run the Application: Start the development server:

npm start

Open your browser and navigate to http://localhost:3000 to see the data fetched from the .NET API displayed in your React application.

Conclusion

Integrating a React frontend with a .NET API backend is a common practice in modern web development. By using libraries like Axios or the built-in Fetch API, you can easily fetch data from a .NET API and display it in your React application. Proper handling of asynchronous operations and error handling ensures a smooth user experience. In the next blog, we’ll explore more advanced topics, such as authentication and authorization in a React and .NET application. Stay tuned!

More from this Series

This blog is part of my series “Building Dynamic Web Apps: React and .NET Unleashed”. If you found this helpful, be sure to check out the other posts in the series:

--

--