Untitled
import userApi from "./apis/user-api"; import postApi from "./apis/post-api"; import { Table, Pagination, Navbar, Container, Accordion, Row, Col, Form, } from "react-bootstrap"; import { useState, useEffect } from "react"; import { Link } from "react-router-dom"; function App() { let [items, setItems] = useState([]); let [users, setUsers] = useState([]); let [posts, setPosts] = useState([]); let [modelValue, setModelValue] = useState({}); let [currentUserId, setCurrentUserId] = useState(""); async function getUsers() { try { let users = []; if(!currentUserId) { users = await userApi.getUsers(); let posts = await postApi.getPosts(); } else { users = await userApi.getUserById(currentUserId); let posts = await postApi.getPosts(); } users = users.map((user) => { let userPosts = posts.filter((post) => post.userId === user.id); return { ...user, posts: userPosts, }; }); setUsers(users); setPosts(posts); } catch (error) { console.error(error); } } function handleChange(event) { let userId = event.target.value; console.log(userId) setCurrentUserId(userId); } useEffect(() => { getUsers(); }, [currentUserId]); return ( <> <Row> <Col md={3}> <h3>Filter by users</h3> <Form.Select onChange={handleChange}> <option value="">-- Select a user --</option> {users.map((user) => ( <option key={user.id} value={user.id}> {user.name} </option> ))} </Form.Select> </Col> <Col> <h3>List post of users</h3> <Form.Control placeholder="Search by name of user..." type="text" /> <Accordion> {users.map((user) => ( <Accordion.Item key={user.id} eventKey={user.id}> <Accordion.Header>{user.name}</Accordion.Header> <Accordion.Body> {user.posts.map((post, index) => ( <div> {index} - <Link to={`posts/${post.id}`}> {post.title}</Link> </div> ))} </Accordion.Body> </Accordion.Item> ))} </Accordion> </Col> </Row> </> ); } export default App;
Leave a Comment