import axios from 'axios' import { useState } from 'react' import { useBooks } from '../context/BooksContext.jsx' const OPEN_LIBRARY_SEARCH = 'https://openlibrary.org/search.json' function docToBookPayload(doc) { return { title: doc.title || 'Sans titre', author: Array.isArray(doc.author_name) ? doc.author_name[0] : 'Auteur inconnu', year: typeof doc.first_publish_year === 'number' ? doc.first_publish_year : new Date().getFullYear(), genre: Array.isArray(doc.subject) ? doc.subject[0] : '', price: 10, read: false, } } function resultKey(doc, index) { return doc.key || doc.cover_edition_key || `${doc.title || 'work'}-${index}` } export default function SearchPage() { const { postBook } = useBooks() const [q, setQ] = useState('') const [loading, setLoading] = useState(false) const [error, setError] = useState(null) const [docs, setDocs] = useState([]) const [addedKeys, setAddedKeys] = useState(() => new Set()) const [lastQuery, setLastQuery] = useState('') async function handleSearch(e) { e.preventDefault() const term = q.trim() if (!term) return setLoading(true) setError(null) setDocs([]) setAddedKeys(() => new Set()) setLastQuery(term) try { const { data } = await axios.get(OPEN_LIBRARY_SEARCH, { params: { q: term, limit: 15 }, timeout: 15000, }) setDocs(Array.isArray(data.docs) ? data.docs : []) } catch (err) { setError( err.response?.data?.error || err.message || 'Impossible de contacter Open Library.', ) } finally { setLoading(false) } } function handleAdd(doc, index) { postBook(docToBookPayload(doc)) const k = resultKey(doc, index) setAddedKeys((prev) => new Set(prev).add(k)) } return (
Interroge l’API publique Open Library avec Axios, puis ajoute un ouvrage à ton catalogue local.
{error ? ({error}
) : null} {!loading && docs.length === 0 && !error && !lastQuery ? (Saisis un mot-clé et lance la recherche.
) : null} {!loading && docs.length === 0 && !error && lastQuery ? (Aucun résultat pour « {lastQuery} ».
) : null} {docs.length > 0 ? ({authors} · {year}