로딩, 에러 상태

유석현(SeokHyun Yu)·2022년 11월 23일
0

React

목록 보기
16/21
post-thumbnail

Product.jsx

import React from "react";
import { useEffect } from "react";
import { useState } from "react";

export default function Product() {
  	// 무언가를 로딩할 때 사용할 state
    const [loading, setLoading] = useState(false);
  
	// 에러가 났을 때 사용할 state
    const [error, setError] = useState(undefined);
  
    const [products, setProducts] = useState([]);
    const [checked, setChecked] = useState(false);
    const handleChange = () => {
        setChecked((prev) => !prev);
    };

    useEffect(() => {
        setLoading((prev) => !prev);
        fetch(`data/${checked ? "sale_" : ""}products.json`)
            .then((res) => res.json())
            .then((data) => {
                setProducts(data);
            })
            .catch((e) => {
                setError(e);
            })
            .finally(() => {
                setLoading((prev) => !prev);
            });

        return () => {
            console.log("clear!");
        };
    }, [checked]);

  	// loading의 상태가 true로 바뀌면 
    if (loading) {
        return <p>Loading...</p>;
    }

  	// error의 상태가 true로 바뀌면 
    if (error) {
        return <p>error</p>;
    }

    return (
        <div>
            <input id="checkbox" type="checkbox" onChange={handleChange} />
            <label htmlFor="checkbox">SALE</label>
            <ul>
                {products.map((product, index) => {
                    return (
                        <li key={index}>
                            <article>
                                <h3>{product.name}</h3>
                                <p>{product.price}</p>
                            </article>
                        </li>
                    );
                })}
            </ul>
        </div>
    );
}
profile
Backend Engineer

0개의 댓글