Home>
There is a component that displays ads loaded from the server. They must be loaded in 10 pieces.
const Adverts= ()=> {
const [adverts, setAdverts]= useState([]);
const getAdverts= async(e)=> {
const code= e.keyCode || e.which;
if (code=== 13) {
try {
const res= await axios.get("http://localhost:5000/api/adverts");
console.log(res.data);
setAdverts(res.data);
} catch (err) {
console log(err)
}
}
};
useEffect(()=> {
document.addEventListener("keydown", getAdverts);
return()=> {
document.removeEventListener("keydown", getAdverts);
};
});
return (
<div style={{ display: "flex", flexDirection: "column" }}> {adverts.map((item)=> (
<Advert item={item} key={item.id} /> ))}
</div> );
};
export default Adverts;
How can I make it so that when I press F7, the next 10 ads are loaded and so on until they run out? It is not possible to return to previous downloaded ads.
-
Answer # 1
You need to make a condition for checking code 137(F7). You also need to change the code if you need it to work for your api. I don't know its interface, but I'm assuming it's implemented like this. I would also not recommend doing anything when pressing the F7 button, because. this button is already used by the browser (at least in Chrome)
const Adverts= ()=> { const [adverts, setAdverts]= useState([]); const [advertsPage, setAdvertsPage]= useState(1); const getAdverts= async(e)=> { const code= e.keyCode || e.which; if (code=== 137) { try { const res= await axios.get("http://localhost:5000/api/adverts",{ params: { page:advertsPage, count: 10 } }); console.log(res.data); setAdverts(res.data); } catch (err) { console log(err) } finally { setAdvertsPage(advertsPage + 1) } } }; useEffect(()=> { document.addEventListener("keydown", getAdverts); return()=> { document.removeEventListener("keydown", getAdverts); }; }); return( <div style={{ display: "flex", flexDirection: "column" }}> {adverts.map((item)=> ( <Advert item={item} key={item.id} /> ))} </div> ); }; export default Adverts;
Related questions
- javascript : Why do I get a jsx file instead of js after building a project with webpack using babel
- javascript : How to optimize useSelector redux
- javascript : How to restart an existing React app?
- javascript : The simplest code on React.js does not work
- javascript : React. Send a get request to the server when pressing Enter
- javascript : Running webPack 5 in development mode does not see html page
- javascript : Problem with Route
- javascript : JS: wrap links found inside a string in an element
- javascript : render {routes} in react
is your code not working?
Vladimir2022-01-19 03:27:14