React - The Complete Guide

Section 17: Course Project: The (Better) Food Order App - Applying What We Learned

olivia_yj 2022. 12. 2. 22:29

The goals

💪🏻Adding a Checkout / Order Form

✌🏻Submitting Orders to a Backend Server (Http)

👍🏻Fetching Meals Data

 

 

import { useEffect, useState } from "react";

import Card from "../UI/Card";
import MealItem from "./MealItem/MealItem";
import classes from "./AvailableMeals.module.css";

const AvailableMeals = () => {
  const [meals, setMeals] = useState([]);

  useEffect(() => {
    const fetchMeals = async () => {
      const response = await fetch(
        "https://bbhhh-14575-default-rtdb.europe-west1.firebasedatabase.app/meals.json"
      );
      const responseData = await response.json();

      const loadedMeals = [];

      for (const key in responseData) {
        loadedMeals.push({
          id: key,
          name: responseData[key].name,
          description: responseData[key].description,
          price: responseData[key].price,
        });
      }

      setMeals(loadedMeals);
    };

    fetchMeals();
  }, []);

  const mealsList = meals.map((meal) => (
    <MealItem
      key={meal.id}
      id={meal.id}
      name={meal.name}
      description={meal.description}
      price={meal.price}
    />
  ));

  return (
    <section className={classes.meals}>
      <Card>
        <ul>{mealsList}</ul>
      </Card>
    </section>
  );
};

export default AvailableMeals;

When we use 'useEffect' we didn't give it any dependency cause we willl only put data once and don't have to repeat again. So we put dependecy part with space so makes it not update.

 

When we use realtime database we should fix the rules otherwise there can be error by safety policy such as CORS.

 

Loading State

We need to put state to check the loading status, we will use isLoading, setIsLoading in useState

 

 const [isLoading, setIsLoading] = useState(true);

So we added this code to check the status of web page loading

setMeals(loadedMeals);
   setIsLoading(false);

And below the code showing the list of item, since we already show this list we don't need to show loading phrase anymore. So we set it as false

if (isLoading) {
    return (
      <section className={classes.MealsLoading}>
        <p>Loading...</p>
      </section>
    );
  }

Otherwise we will show this Loading phrase to users.

 

Since it was too fast to see, I put throttling and checked that we could see this Loading mark.

 

I didn't set this so I couldn't write on my database xD