First exercises en US - rocambille/start-express-react GitHub Wiki

To familiarize yourself with the framework and check your configuration, here are some simple exercises to perform after installation. These step-by-step exercises will help you understand the fundamentals of StartER.

Exercise 1 : Hello World API

Let's create an endpoint that returns "hello, world!" This will allow us to verify that your setup is working properly and that you understand the basics of Express routing.

Step 1: Create a new module

Create a hello folder in src/express/modules.

Step 2: Create a routes file

Create a helloRoutes.ts file in this folder with the following contents:

import { type RequestHandler, Router } from "express";

const router = Router();

/* ************************************************************************ */

const sayHello: RequestHandler = (_req, res) => {
  res.json({ message: "hello, world!" });
};

/* ************************************************************************ */

router.get("/api/hello", sayHello);

/* ************************************************************************ */

export default router;

Step 3: Integrate the module into the main routes

Modify the src/express/routes.ts file to integrate your new module:

import express, { Router } from "express";

const router = Router().use(express.json());

/* ************************************************************************ */

import authRoutes from "./modules/auth/authRoutes";
router.use(authRoutes);

/* ************************************************************************ */

import itemRoutes from "./modules/item/itemRoutes";
router.use(itemRoutes);

/* ************************************************************************ */

import userRoutes from "./modules/user/userRoutes";
router.use(userRoutes);

/* ************************************************************************ */

import helloRoutes from "./modules/hello/helloRoutes";
router.use(helloRoutes);

/* ************************************************************************ */

export default router;

Step 4: Test the endpoint

Restart your server if necessary and visit http://localhost:5173/api/hello in your browser or use a tool like cURL or Postman. You should see the JSON response with the message "hello, world!"

Exercise 2: Create an "About" page

Now, let's create a React page that will display a message and allow us to understand client-side routing.

Step 1: Create a page component

Create an About.tsx file in the src/react/pages folder:

function About() {
  return (
    <>
      <h1>À propos</h1>
      <p>StartER rocks !</p>
    </>
  );
}

export default About;

Step 2: Add the route to the routes.tsx file

Modify the src/react/routes.tsx file to integrate your new page:

import { Suspense } from "react";
import { Outlet } from "react-router";

import { ItemProvider } from "./components/ItemContext";
import Layout from "./components/Layout";

import About from "./pages/About";
import Home from "./pages/Home";
import ItemCreate from "./pages/ItemCreate";
// ...

import "./index.css";

export default [
  {
    path: "/",
    element: (
      <Layout>
        <Outlet />
      </Layout>
    ),
    children: [
      {
        index: true,
        element: <Home />,
      },
      {
        path: "/about",
        element: <About />,
      },
      // ...
    ],
  },
];

Step 3: Update the navigation

Modify the NavBar component to include a link to your new page. Open the src/react/components/NavBar.tsx file and add a new element to the navigation.

Step 4: Test the Page

Visit http://localhost:5173/about in your browser. You should see your new page.

Exercise 3: Connecting the frontend to the backend

For our final exercise, let's connect our frontend to the backend API we created in Exercise 1.

Step 1: Add the fetch functionality to About.tsx

Modify the About.tsx file:

import { useState, useEffect } from "react";

function About() {
  const [message, setMessage] = useState("");
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchHello = async () => {
      try {
        const response = await fetch("/api/hello");
        const data = await response.json();
        setMessage(data.message);
      } catch (error) {
        console.error("Erreur lors de la récupération du message:", error);
        setMessage("Erreur de chargement");
      } finally {
        setLoading(false);
      }
    };

    fetchHello();
  }, []);

  return (
    <>
      <h1>À propos</h1>
      <p>StartER rocks !</p>

      {loading ? (
        <p>Chargement du message...</p>
      ) : (
        <p>Message de l'API : "{message}"</p>
      )}
    </>
  );
}

export default About;

Step 2: test the integration

Reload the http://localhost:5173/about page. You should now see the "hello, world!" message retrieved from your API.

Congratulations!

You have completed the introductory exercises for StartER! You have learned how to:

  1. Create an API endpoint with Express
  2. Create a React page with routing
  3. Connect your React frontend to your Express backend

These basic skills will allow you to further explore the framework and build more complex features.

Refer to the following pages for more details:

⚠️ **GitHub.com Fallback** ⚠️