4

How do we get records from a table by pages?

My requirement: I have a table with 100 records and want to display all these records in my front-end-application with 10 records per page and if the user hits the 'Next'-button, the records from the next page (e.g 11 to 20, 21 to 30 etc.) have to be queried.

Likewise when hitting the 'Prev'-button, the previous 10 records have to queried. How can I implement this logic using EOSJS's(V20.0.0) and the get_table_rows()-endpoint?

1

This has its limitations but if you are fetching a table by the primary key which is an incremented integer value, you could use a combination of lower_bound, upper_bound, and limit and do something like this:

// base setup
var pageSize = 10
var curLower = 0
var curUpper = pageSize - 1
// fetch first page
fetchRows(curLower, curUpper, pageSize) 

// next btn click
handleNext(curLower, curUpper, pageSize) {
  curLower = curUpper + 1
  curUpper += pageSize
  const res = fetchRows(curLower, curUpper, pageSize)
  if(res.rows.length < pageSize) {
    curUpper = curLower + res.rows.length - 1
    // handle last page
  }
}

// prev btn click
handlePrev(curLower, curUpper, pageSize) {
  curUpper = curLower - 1
  curLower -= pageSize
  const res = fetchRows(curLower, curUpper, pageSize)
  if(curLower == 0) {
    // handle first page
  }
}

async fetchRows(lower, upper, pageSize) {
  const res = await rpc.get_table_rows({
    json: true,              
    code: <my_contract>,     
    scope: <my_scope>,         
    table: <my_table>,        
    limit: pageSize,               
    reverse = false,         
    lower_bound = lower,
    upper_bound = upper
  })
  return res
}

Needs more handling for stuff like res.rows.length < pageSize in first page, handling of results that aren't first/last page... but you get the point.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.