To connect your ASP.NET Core Web API with a React frontend and perform CRUD operations, follow these steps:
1. Set up your React Project
If you haven't already, create 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.