🔨 Affichage des items dans les rooms dans la home

This commit is contained in:
Votre Nom 2024-03-27 19:07:49 +01:00
parent bcac0d2a4b
commit e1897ca11a
2 changed files with 54 additions and 2 deletions

View File

@ -0,0 +1,52 @@
import React, { useState, useEffect } from "react";
import axios from "axios";
export const RoomItemsList = () => {
const [rooms, setRooms] = useState([]);
useEffect(() => {
const fetchRoomsAndItems = async () => {
try {
const response = await axios.get(
`${import.meta.env.VITE_API_URL}/room`,
);
const roomsWithItems = await Promise.all(
response.data.map(async (room) => {
const itemsResponse = await axios.get(
`${import.meta.env.VITE_API_URL}/item?room=${room._id}`,
);
const itemsForThisRoom = itemsResponse.data.filter(
(item) => item.room === room._id,
);
return { ...room, items: itemsForThisRoom };
}),
);
setRooms(roomsWithItems);
} catch (error) {
console.error(error);
}
};
fetchRoomsAndItems();
}, []);
return (
<div>
{rooms.map((room) => (
<div key={room._id}>
<h2>{room.name}</h2>
{Array.isArray(room.items) &&
room.items.map((item) => {
return (
<div key={item._id}>
<p>{item.brand}</p>
<p>{item.model}</p>
<p>{item.price}</p>
</div>
);
})}
</div>
))}
</div>
);
};

View File

@ -4,18 +4,18 @@ import { useAuth } from "../hooks";
import { DatePicker } from "antd"; import { DatePicker } from "antd";
import { FormCreateItem } from "../components/form/formCreateItem"; import { FormCreateItem } from "../components/form/formCreateItem";
import { FormCreateRoom } from "../components/form/formCreateRoom"; import { FormCreateRoom } from "../components/form/formCreateRoom";
import { ItemPage } from "../components/item/ItemPage"; import { RoomItemsList } from "../components/item/RoomItemsList";
export const Home = () => { export const Home = () => {
const { user } = useAuth(); const { user } = useAuth();
return ( return (
<div> <div>
<h1>Home page</h1> <h1>Home page</h1>
{user && <h2>Hello {user.user.username}</h2>} {user && <h2>Hello {user.user.username}</h2>}
<FormCreateRoom></FormCreateRoom> <FormCreateRoom></FormCreateRoom>
<FormCreateItem></FormCreateItem> <FormCreateItem></FormCreateItem>
<RoomItemsList></RoomItemsList>
</div> </div>
); );
}; };