'Pokemon API request generate 5 Pokémon at a time
I need help with how to fetch 5 random pokemon at a time instead of rendering all pokemon on the screen using react?
// destructuring
const [items, setItems] = useState([]);
const rootApi = 'https://pokeapi.co/api/v2/pokemon/';
// fetch Pokemon
useEffect(() => {
const id = Math.floor(Math.random() * 800);
const fetchItems = async (id) => {
const response = await axios.get(rootApi + id);
setItems([...items, response.data]);
};
fetchItems(id);
}, [items]);
Solution 1:[1]
generate offset randomly each time, and fetch 5 pokemons it will fetch you 5 consecutive pokemons. you can also fetch all pokemons once and randomly choose 5 indexes. here is sample code. codesandbox https://codesandbox.io/s/gallant-davinci-jfutn?file=/src/App.js:0-946
import { useState, useEffect } from "react";
import axios from "axios";
function getUrl(limit, offset) {
return `https://pokeapi.co/api/v2/pokemon/?limit=${limit}&offset=${offset}`;
}
export default function App() {
const [items, setItems] = useState([]);
const [offset, setOffset] = useState(Math.floor(Math.random() * 1000));
const generateNewId = () => {
const id = Math.floor(Math.random() * 1000);
setOffset(id);
};
// fetch Pokemon
useEffect(() => {
const fetchItems = async (offset) => {
const response = await axios.get(getUrl(5, offset));
const data = response.data;
setItems([...items, ...data.results]);
};
fetchItems(offset);
}, [offset]);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
{items && items.map((item) => <p key={item.url}>{item.name}</p>)}
<button onClick={generateNewId}>fetch 5 pokemon</button>
</div>
);
}
Solution 2:[2]
I don't know if this is exactly what you want:
Solution 1: You can make requests on all pages and save them in a state Array. Every time you make a request on a page, you can make a spread operator on your array and add the new response. But this solution will take a long time as this api is over 1100 pages long.
Solution 2: You can draw 5 integer values ??(between 1 and the number of pages), and, according to the number that comes out, you make the request on the page drawn. With the response to the request, you make another sort and catch the first pokemon and store it in a state Array. Repeat this operation 4 more times, or as many times as you like. In the end, just render the array with the pokemons drawn!
At first it was these two solutions that came to my mind! If this is in line with your question, good luck!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | General Grievance |