Wednesday 14 August 2024

Integrating ASP.NET Core Web API with React frontend

Leave a Comment

To accomplish CRUD operations, link your ASP.NET Core Web API to a React frontend by following these steps:

1. Create a React project
If it's not already done so, start a new React project.

npx create-react-app my-app
cd my-app

2. Install Axios
Axios is a popular library for making HTTP requests in React

npm install axios

3. Create a Service to Handle API Calls
Create a file called apiService.js in your src folder.

4. Implement CRUD Operations in React
In your App.js or any component where you want to perform CRUD operations, import the service and use it.

import React, { useState, useEffect } from 'react';
import { getItems, createItem, updateItem, deleteItem } from './apiService';
function App() {
  const [items, setItems] = useState([]);
  const [newItem, setNewItem] = useState('');
  useEffect(() => {
    loadItems();
  }, []);
  const loadItems = async () => {
    const response = await getItems();
    setItems(response.data);
  };
  const handleCreate = async () => {
    await createItem({ name: newItem });
    loadItems();
    setNewItem('');
  };
  const handleUpdate = async (id) => {
    await updateItem(id, { name: 'Updated Item' });
    loadItems();
  };
  const handleDelete = async (id) => {
    await deleteItem(id);
    loadItems();
  };
  return (
    <div>
      <h1>Items</h1>
      <ul>
        {items.map(item => (
          <li key={item.id}>
            {item.name}
            <button onClick={() => handleUpdate(item.id)}>Update</button>
            <button onClick={() => handleDelete(item.id)}>Delete</button>
          </li>
        ))}
      </ul>
      <input
        type="text"
        value={newItem}
        onChange={(e) => setNewItem(e.target.value)}
      />
      <button onClick={handleCreate}>Add Item</button>
    </div>
  );
}
export default App;

5. Test your application
Run your React app using.

npm start

Ensure your ASP.NET Core Web API is running, and test your application by performing CRUD operations from the React frontend.

6. CORS Configuration (if needed)
If you face CORS issues, ensure your ASP.NET Core Web API allows requests from your React app. In your Startup. cs, configure CORS.

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowAll",
            builder =>
            {
                builder.AllowAnyOrigin()
                       .AllowAnyMethod()
                       .AllowAnyHeader();
            });
    });
    services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseCors("AllowAll");
    app.UseRouting();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

This setup should get you started with integrating React with your ASP.NET Core Web API for performing CRUD operations.

ASP.NET Core 9.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 9.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

0 comments:

Post a Comment