Middle
Get data about books and their authors. Display the data in a paginated list with 10 books per page in the format: <book title> - <author> api: [link] specification: [link] if swagger does not open, in the root sber-c55-books-mock-1.0.1-oas3.1-resolved.yaml const PAGE_SIZE = 10; export default function App() { const [books, setBooks] = useState([]) const [page, setPage] = useState(1); const [loading, setLoading] = useState(false) useEffect(() => { setLoading(true); fetch('[link]') .then((res) => res.json()) .then((data) => setBooks(data)) .finally(() => setLoading(false)); }, []); const totalPage = Math.ceil(books.length / PAGE_SIZE); const start = (page - 1) * PAGE_SIZE; const currentBooks = books.slice(start, start + PAGE_SIZE); return ( <div className="App"> {loading && <p>Loading...</p>} <ul> {currentBooks.map((book) => ( <li key={book.id}>{book.title} - {book.author}</li> ))} </ul> <button onClick={() => setPage((prev) => Math.max(prev - 1, 1))} disabled={page === 1}>Previous</button> <button onClick={() => setPage((prev) => Math.min(prev + 1, totalPage))} disabled={page === totalPage}>Next</button> </div> ); } Fix errors and implement paginated list display of books with authors.
sobes.tech AI
Answer from AI
Your code has several errors and shortcomings:
- In
useEffect, the dependencies array is missing, which causes the request to run on every render. - In
finally, there is a syntax error:() =instead of() =>. - The variable
startis not defined for slicing the array. - Inside JSX within
map, there is noreturnand nokeyattribute.
Here's a corrected and improved version:
import React, { useState, useEffect } from 'react';
const PAGE_SIZE = 10;
export default function App() {
const [books, setBooks] = useState([]);
const [page, setPage] = useState(1);
const [loading, setLoading] = useState(false);
useEffect(() => {
setLoading(true);
fetch('[link]')
.then((res) => res.json())
.then((data) => setBooks(data))
.finally(() => setLoading(false));
}, []); // empty dependencies array — request runs once on mount
const totalPage = Math.ceil(books.length / PAGE_SIZE);
const start = (page - 1) * PAGE_SIZE;
const currentBooks = books.slice(start, start + PAGE_SIZE);
return (
<div className="App">
{loading && <p>Loading...</p>}
<ul>
{currentBooks.map((book) => (
<li key={book.id}>
{book.title} - {book.author}
</li>
))}
</ul>
<div>
<button disabled={page <= 1} onClick={() => setPage(page - 1)}>
Back
</button>
<span> Page {page} of {totalPage} </span>
<button disabled={page >= totalPage} onClick={() => setPage(page + 1)}>
Next
</button>
</div>
</div>
);
}
Note that:
- Buttons for page navigation are added.
keyis used in the list.- The syntax of
finallyis corrected. - The dependencies array is added to
useEffect.
This will correctly load data, display it paginated by 10 books, and allow page switching.