I am trying use the pokeApi for a site but my function doesn't work the second time.
The result in next = the next link I want to use that the Api returns.
const beginLink = "https://pokeapi.co/api/v2/pokemon/";
let next;
let previous;
apiCall(beginLink);
function apiCall(link) {
$('#pokemons').html(``);
$.ajax({
url: link
}).done(handleResponse);
function handleResponse(data) {
next = data.next;
previous = data.previous;
for (let i = 0; i < 20; i++) {
$('#pokemons').append(`<div class="pokemon"><img src="https://raw.githubusercontent.com/msikma/pokesprite/master/pokemon-gen8/regular/${data.results[i].name}.png"><br><p>${data.results[i].name}</p></div>`);
}
}
}
$("#next").on("click ", apiCall(next));
The main issue is because apiCall(next) doesn't return a function. Therefore, when the click event occurs nothing happens.
To fix this issue, and also to remove the reliance on global variables which should avoided, you can place the URL of the next call in to the data held by the #next element. This way the function which updates the content of the DOM based on the AJAX response is entirely self-contained.
let $next = $('#next');
let $pokemonContainer = $('#pokemons');
function apiCall() {
$pokemonContainer.empty();
$.get($next.data('url')).done(handlePokemonApiResponse);
}
function handlePokemonApiResponse(data) {
$next.data('url', data.next);
let html = data.results.map(p => `<div class="pokemon"><img src="https://raw.githubusercontent.com/msikma/pokesprite/master/pokemon-gen8/regular/${p.name}.png"><br><p>${p.name}</p></div>`);
$pokemonContainer.html(html);
}
$next.on("click", apiCall).trigger('click');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button type="button" id="next" data-url="https://pokeapi.co/api/v2/pokemon/">Next</button>
<div id="pokemons"></div>