단순 코드 기록/React

React_Loader의 분리

일일일코_장민기 2024. 3. 21. 14:51
728x90
import HomePage from "./pages/Home"
import Products from "./pages/Products"
import RootLayout from "./pages/root";
import Error from "./pages/Error";
import ProductDetail from "./pages/ProductDetail"                  
import ProductDetail2 from "./pages/ProductDetail2"                
import Users, {loader as usersLoader} from "./pages/Users"              //Alias
import { createBrowserRouter, RouterProvider } from "react-router-dom"
import axios from "axios";

const router = createBrowserRouter(              
  [{
    path: "/",
    element: <RootLayout/>,
    errorElement: <Error/>,      
   
    id: "root",
    loader: async function(){
      console.log("loader root 사용");
      const response = await fetch("https://reqres.in/api/users?page=1");
      const resData = await response.json();
      return resData.data;
    },

    children: [
      {path: "/", element: <HomePage/>},
      {path: "/products", element: <Products/>},
      {path: "/products/:productId", element: <ProductDetail/>},  
      {path: "/products2/", element: <ProductDetail2/>},        
      {path: "/users/", element: <Users/>, loader: usersLoader
        //async function(){
        // console.log("loader 사용");
        // const response = await fetch("https://reqres.in/api/users?page=2");
        // const resData = await response.json();
        // return resData.data;
        // },
      },        
    ]
  }]
);

export default function App(){

  return(
    <>
      <h1>App</h1>
      <RouterProvider router={router}></RouterProvider>
    </>
  )

}

 

import UserList from "../components/UserList";

export default function Users(){


    return(
        <>
            <h2>Users</h2>
            <UserList></UserList>
        </>
    )
}

export async function loader(){
    console.log("Users.loader 사용");
    const response = await fetch("https://reqres.in/api/users?page=2");
    const resData = await response.json();
    return resData.data;
}

 

import { useLoaderData, useRouteLoaderData } from "react-router-dom";

export default function UserList() {      //수정

  const events = useLoaderData();
  //const events = useRouteLoaderData로("root"); //아이디를 지정하는 useRouteLoaderData로 변경

  return (
    <>
      <h3>UserList</h3>
      <table border={1}>
        <tr>
          <th>아이디</th>
          <th>이메일</th>
          <th></th>
          <th>이름</th>
          <th>이미지</th>
        </tr>
        {events.map((row, idx) => (
          <tr key={idx}>
            <td>{row.id}</td>
            <td>{row.email}</td>
            <td>{row.first_name}</td>
            <td>{row.last_name}</td>
            <td>
              <img src={row.avatar} alt={`User ${row.id} avatar`}></img>
            </td>
          </tr>
        ))}
      </table>
    </>
  );
}