Exercise 5.4C: Migrate Professionals and Services Pages

Purpose: To incorporate the Professionals and Services pages into React, which require fetching data from the Server.

Step 1. React: Create ProfessionalsList and ServicesList Components

In reactapp/src/containers, create ProfessionalsList.jsx and ServicesList.jsx. The goal is to very similar to the goal of the professionals_list.html and services_list.html files created in Project Part 4. They will be used in the Professionals and Add Professionals pages, the Services and Add Services pages, and help refresh lists. Instead of HTML templates, we will create them as React components. Since their data comes from the database, we will ultimately have them fetch data from the server in JSON (see Step 3 below).

Copy the HTML / Jinja from your flaskapp/templates directory and translate to JSX where needed. In each component, create a useState variable to represent the list, in JSON, of professionals or services. For now, initialize that useState variable to a dummy value or an empty value.

Step 2. Flask: Convert /professionals and /services Routes from UI to API

Getting the JSON data from your Flask server is actually shockingly easy. You already have routes for "/professionals" and "/services". Currently, they run get_professionals() or get_services() model functions and pass the data to render_template. Now, you simply need to pass the data to the "jsonify" function instead of render_template (you'll need to import "jsonify" from Flask).

app.py
(professionals route)

Step 3. Make ProfessionalsList and ServicesList Fetch Data with AJAX

Your ProfessionalsList and ServicesList components already have a useState variable that expects JSON. To fetch this data from your Flask server's newly modified "/professionals" and "/services" routes, the solution resembles the optional FlaskPatch code provided in Exercise 5.4A. The following example fetches from the server:

ProfessionalsList.jsx

Note how the .json() function is used instead of the .text() function. Ultimately, all responses come in text, but the .json() function parses the text and turns it into an object if it is valid JSON.

Take time to understand the way useEffect calls getProfessionals, which calls fetch, which updates the state variable, which then causes a re-render. Use that understanding to implement ServicesList.jsx, which is a little more complicated. If it simplifies your task, you may choose to omit or comment out the <form> portion of ServicesList in this exercise. If you do, you will add it back in the next exercise.

Step 4. Finish Migrating Professionals and Services Pages

Now, copy the contents of flaskapp/templates/professionals.html and flaskapp/templates/services.html into reactapp/src/pages/Professionals.jsx and reactapp/src/pages/Services.jsx and translate into JSX. This should be fairly simple after converting the ProfessionalsList and ServicesList components.