I’m working with a database API and need help updating a URL parameter when someone clicks a button. Here’s my current setup:
var category = "Deals"
var auth_token = "?key=abcdef"
var recordLimit = "&limit=5"
var queryFilter = "&filter=%7Bstatus%7D%3D%22active%22"
var pageToken = "";
var apiUrl = "https://api.database.com/v1/base789/" + category + auth_token + recordLimit + "&pageToken=" + pageToken + "&sort=deal_id";
async function fetchData() {
const result = await fetch(apiUrl);
const info = await result.json();
// process data...
}
I also made a function to update the page token:
var loadNext = function () {
console.log(pageToken);
pageToken = info.nextPageToken;
console.log(pageToken);
}
nextButton.onclick = loadNext;
The problem is I want the button click to actually update the pageToken value and fetch new results. Right now it just logs the values but doesn’t reload the data with the new parameter.
How can I make the button properly change the API parameter and get fresh data? Any suggestions would be helpful!
<div class="content-area" id="container">
</div>
Your apiUrl gets built once with an empty pageToken and stays that way. You’ve got to rebuild it each time.
Here’s how I handle this:
function buildApiUrl() {
return "https://api.database.com/v1/base789/" + category + auth_token + recordLimit + "&pageToken=" + pageToken + "&sort=deal_id";
}
async function fetchData() {
const result = await fetch(buildApiUrl());
const info = await result.json();
// process data...
return info; // return so you can access it elsewhere
}
var loadNext = async function () {
const info = await fetchData(); // get current data first
pageToken = info.nextPageToken;
await fetchData(); // fetch again with new token
}
The URL gets built fresh every time with whatever pageToken is current. I’ve done this in dozens of paginated APIs - works every time.
Just watch your variable scope so nextPageToken is there when you need it.
Your problem is you’re updating pageToken but not rebuilding the apiUrl with the new value. You construct the URL once at the start, so when pageToken changes, the URL doesn’t. Fix this by rebuilding the complete URL string inside loadNext after updating pageToken, then call fetchData() again. I’d move URL construction into a separate function you can call whenever parameters change. Also check that the info variable with nextPageToken is accessible where loadNext runs - otherwise you’ll get undefined values.
ur super close! just make sure to set the pageToken and call fetchData() again to get the new results. also, update apiUrl with the new pageToken before your fetch. that should do it!