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]);
CodePudding user response:
Olá, não sei se é exatamente o que você quer:
Solução 1: Você pode fazer as requisições em todas as páginas e guardar em um state Array. Cada vez que você faz uma requisição em uma página, você pode fazer um spread operator no seu array e adicionar a nova response. Mas essa solução vai demorar muito, pois esta api tem mais de 1100 páginas.
Solução 2: Você pode sortear 5 valores inteiros (entre 1 e a quantidade de páginas), e, de acordo com o número que sair, você faz a requisição na página sorteada. Com a resposta da requisição, você faz outro sort e pega o primeiro pokemon e guarda num state Array. Repete essa operação mais 4 vezes, ou quantas quiser. No final é só renderizar o array com os pokemons sorteados!
A princípio foi essas duas soluções que me veio na mente! Se for na linha de raciocínio da sua pergunta, boa sorte!
translated with google translate:
Hi, 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!
CodePudding user response:
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';
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 fetch(getUrl(5,offset));
const data = await response.json();
setItems(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>
);
}
