Navigating through tables in nuxt js is made easier with pagination

I am trying to dynamically retrieve the total number of pages from my API response header, which includes "x-total-count = 50". However, I am struggling to figure out how to access this variable in my frontend. Here is a snippet of my code:

const sort = ref({ column: 'licensePlate', direction: 'asc' as const })
const page = ref(1)
const pageCount = ref(10)
const pageTotal = ref(50)   //This value should be dynamic coming from the API 
const pageFrom = computed(() => (page.value - 1) * pageCount.value + 1)
const pageTo = computed(() => Math.min(page.value * pageCount.value, pageTotal.value))

// Data
const { data: cars, status} = await useLazyAsyncData<{
  licensePlate: string
  arrivalDate: string
  charge: number

}[]>('cars', (response) => ($fetch as any)(`http://localhost:3001/deported`, {
  query: {
    q: search.value,
    '_page': page.value,
    '_limit': pageCount.value,
    '_sort': sort.value.column,
    '_order': sort.value.direction
  }
}), {
  default: () => [],
  watch: [page, search, pageCount, sort]
})

I have not been successful in attempting any solutions so far.

Answer №1

One way to fetch data and access response headers is by using raw fetch method like this:

const { info } = useAsyncData(async () => {
  const reply = await $fetch.raw('http://localhost:3001/deported', {
    query: {
      q: search.value,
      _page: page.value,
      _limit: pageCount.value,
      _sort: sort.value.column,
      _order: sort.value.direction,
    },
  });
  const total = reply.headers.get('x-total-count');
  totalPages.value = total ? +total : 0;
  /** Assuming the response is in JSON format */
  return await reply.json();
});

Extracted from ofetch documentation (framework used by nuxt)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing coordinate formatting in JavaScript [Node.js]

I'm looking to tweak the JSON output into this specific format: [ 50.87758, 5.78092 ], [ 52.87758, 5.48091 ] and so on. Currently, the output looks like this: [ { lat: 53.1799, lon: 6.98565 }, { lat: 52.02554, lon: 5.82181 }, { lat: 51.87335, l ...

What is the smallest server.js file needed to run a react/redux application?

I have successfully configured my project using webpack and babel for ES6 transpilation with the specified presets: { "presets": ["react", "es2015", "stage-1"] } My webpack production configuration is structured as follows: var path = require('pa ...

Is it possible to utilize a computed property for dynamically styling a table row based on certain conditions?

I have a table of users that I am currently rendering, and my goal is to highlight the entire row only for the current user. My initial thought was to use a computed property to achieve this, but I seem to be facing some difficulties in making it work. I ...

Retrieving a specific item from a JSON object within the AJAX success function

Utilizing the ajax call below to retrieve a JSON object from the server side (PHP) $.ajax({ url: endpoint, method: "POST", data: { id : userId }, dataType: "json", success: function(result) { $("#itemName").val(result.itemNa ...

What is the best way to prevent a draggable div from moving past the edge of the viewport?

My situation involves a draggable div that functions as a popup window when a specific button is clicked. However, I noticed that dragging the div to the end of the viewport allows me to drag it out of the visible area, causing the body of the page to expa ...

Creating a showcase page that generates its own code: A guide

If you have created a demo page for your product and want to include a button at the bottom that, when clicked, displays the source code of the demo above, how can you accomplish this in an elegant way? ...

Iterate through an array of objects and add them to a fresh array

I am encountering an issue where I would like to generate a fresh array of objects in order to avoid utilizing a nested array map. However, the error message below is being displayed: TypeError: Cannot read property 'subscriber_data' of undefine ...

Exploring the capabilities of AngularJS for efficient testing using Jasmine alongside mixpanel integration

Within my AngularJS application, I implement MixPanel for analytics by using the asynchronous script in my index.html file. index.html <script type="text/javascript">(function(e,b){if(!b.__SV){var a,f,i,g;window.mixpanel=b;a=e.createElement("script ...

What could be causing my handle button to slide off the timeline towards the right?

I'm facing an issue with my volume bar component where the slider button is rendering outside of the timeline instead of on top of the progress bar. I need assistance in adjusting its position. // Here is the code for my volume bar component: import ...

Tracking the progress bar as files are being uploaded via AJAX using HTML5

Currently, I have a progress bar that increments based on the number of files and their sizes. I am looking to implement an overall progress bar to display while uploading files to the server using AJAX and HTML5. Each file is uploaded individually to th ...

A loop that incorporates a jQuery JavaScript dropdown menu along with some calculations

My goal is to have multiple dropdown lists populated from a PHP while loop. Each select dropdown has a corresponding textbox that should update its value when a selection is made. However, the current script only works for a single dropdown outside of the ...

PHP cannot be utilized within the script tag

I'm currently using JavaScript to display an error message If a user inputs incorrect information and I add the following code: <?php $_POST["usernamereg"] ?> = usernamereg; the alert function stops working. However, if I remove this code, t ...

How to accurately incorporate the "HH:MM" time format into a Date Object in JavaScript

I need to convert a specific time of the day into a Date Object. The time is in String format and is in CET (Central European Time). In CET, "16:00" translates to "15:00" in UTC during Winter time. The code snippet below achieves this conversion in node.js ...

"Shopping just got easier with our new drag and drop feature! Simply drag items

I want to develop a Virtual Shopping Cart system. Items will be retrieved from a database. A virtual basket will be available. Users can drag items and drop them into the basket, similar to shopping in a mall. Once the user clicks the save button, the s ...

Is NextJS rendering solely on the server, or is it capable of rendering on both

Within my users.js JSX file, I have an exported component that looks like this: ... return <MainContainer keywords="users"> export default Users During the process of SSR/SSG, the browser displays the users HTML (comprising of <li> t ...

Collecting values using AJAX in Codeigniter from an input file

I have been exploring examples of AJAX code, and I noticed that when using form-data in AJAX, we need to serialize each element individually. While normal data serialization works fine, I encountered an issue when trying to pass the value of an input file ...

Is it possible to execute a function before or after each method of a factory or class is called in AngularJS or JavaScript?

In various programming languages such as Java, Ruby, and others, there is often a functionality to call a function before or after a method is executed. This feature is commonly provided by the frameworks being used. For example, Jasmine (a unit-testing li ...

Do you have any recommendations to help me achieve the sticky footer hack?

Check out this awesome website: I've been working on incorporating a responsive design with a sticky footer, but I encountered some issues with incompatible CSS options. The fixed option wasn't meeting my needs either. For the homepage, I have ...

Optimizing Google e2e testing using Protractor

Improving login efficiency is necessary to enhance the speed of executing e2e tests. At present, after every test, the Chrome browser shuts down, requiring a new login session for each subsequent test. What changes can be made to address this issue? Any ...

Tips for integrating Google WebKit with AngularJS

Looking to enhance my application with Google WebKit functionality. My goal is to create a feature similar to Gmail's where hovering over the "+" symbol expands to display options such as "insert photos" and "insert links". I'm just starting out ...