1 - Connecting React and ASP.NET Core - Environment Variables - Introduction

3 min read 1 year ago
Published on Aug 05, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

This tutorial will guide you through the initial steps of connecting a React application with an ASP.NET Core backend. You'll learn how to set up both applications and configure their communication. This foundational knowledge is essential for developing full-stack applications that leverage the powerful capabilities of both frameworks.

Step 1: Set Up ASP.NET Core Application

  1. Create a New ASP.NET Core Project

    • Open your terminal or command prompt.
    • Use the following command to create a new ASP.NET Core Web API project:
      dotnet new webapi -n YourProjectName
      
    • Change directory to your project:
      cd YourProjectName
      
  2. Run the Application

    • Start the application to ensure everything is set up correctly:
      dotnet run
      
    • You should see output indicating the application is running, typically at http://localhost:5000.
  3. Verify the API Endpoint

    • Open a web browser and navigate to http://localhost:5000/weatherforecast to see a JSON response, confirming the API is working.

Step 2: Set Up React Application

  1. Create a New React App

    • In a new terminal window, use the following command to create a React application:
      npx create-react-app your-react-app
      
    • Change directory to your React app:
      cd your-react-app
      
  2. Start the React Application

    • Launch the React application:
      npm start
      
    • This will start your React app at http://localhost:3000.

Step 3: Configure Communication Between Applications

  1. Install Axios for API Requests

    • In your React app directory, install Axios to handle HTTP requests:
      npm install axios
      
  2. Create an API Service File

    • Inside the src folder, create a new file named apiService.js.
    • Add the following code to handle GET requests to your ASP.NET Core API:
      import axios from 'axios';
      
      const API_URL = 'http://localhost:5000/weatherforecast';
      
      export const fetchWeatherData = async () => {
        try {
          const response = await axios.get(API_URL);
          return response.data;
        } catch (error) {
          console.error('Error fetching data', error);
          throw error;
        }
      };
      
  3. Fetch Data in a React Component

    • In your App.js file, import the API service and call the fetch function:
      import React, { useEffect, useState } from 'react';
      import { fetchWeatherData } from './apiService';
      
      const App = () => {
        const [weatherData, setWeatherData] = useState([]);
      
        useEffect(() => {
          const getWeatherData = async () => {
            const data = await fetchWeatherData();
            setWeatherData(data);
          };
          getWeatherData();
        }, []);
      
        return (
          <div>
            <h1>Weather Forecast</h1>
            <ul>
              {weatherData.map((item, index) => (
                <li key={index}>{item.summary}</li>
              ))}
            </ul>
          </div>
        );
      };
      
      export default App;
      

Conclusion

In this tutorial, you've learned how to set up an ASP.NET Core Web API and a React application, as well as how to configure them to communicate with each other using Axios. As a next step, you can explore adding more complex API endpoints, handling user input in your React app, or deploying both applications for real-world use.