I'm trying to fetch the author's name in this search bar component. the idea is to fetch the author's name in the search bar and display the author's picture with the author's name. but it's not working for me. Can someone help and explain why this is not working. Thank you.
import { useEffect, useState } from "react";
import "./Searchbar.css";
import axios from "axios";
function Searchbar() {
const [query, setQuery] = useState("");
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
const res = await axios.get(`https://picsum.photos/v2/?=${query}`);
setData(res.data);
};
if (query.length === 0 || query.length > 2) fetchData();
}, [query]);
return (
<div className="app">
<input
className="search"
placeholder="Search..."
onChange={(e) => setQuery(e.target.value.toLowerCase())}
/>
<div>{data}</div>
</div>
);
}
export default Searchbar;
Your url is wrong.
`https://picsum.photos/v2/?=${query}`
This goes to a bad page. Can you go to picsum.photos and use their available API endpoints accordingly, such as their list endpoint.
https://picsum.photos/v2/list
It looks like there's only a limited number of authors currently so you could fetch it, and store the authors array in data
and then handle the searching separately.
const [query, setQuery] = useState("");
const [data, setData] = useState([]);
// Add one more state to store the authors being searched for
const [searchResults, setSearchResults] = useState([]);
useEffect(() => {
const fetchData = async () => {
const res = await axios.get(`https://picsum.photos/v2/list`);
setData(res.data);
};
fetchData();
}, []);
// Query that handles searching
useEffect(() => {
setSearchResults(data.filter((authorData) => authorData['author'].toLowerCase().includes(query)));
}, [query, data]);
return (
<div className="app">
<input
className="search"
placeholder="Search..."
onChange={(e) => setQuery(e.target.value.toLowerCase())}
/>
<div>{searchResults}</div>
</div>
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.