The subsequent page fails to load. Issue with the pagination feature

I'm currently stuck trying to implement pagination in my task and it's not functioning as expected.

My approach involved creating two buttons with click events attached, along with a data property that changes when the buttons are clicked. This property is then written into the link, consequently updating the display to show the next set of 10 posts.

Despite this setup, something seems to be off and the functionality isn't working as intended. I would greatly appreciate any insights on where I might be going wrong, as well as recommendations for articles related to pagination.

Here is a snippet of my HTML:

  <button type="button" @click="counter -=1" class="prev">Prev</button>
  <div class="counter">{{ counter }}</div>
  <button type="button" @click="counter +=1" class="next">Next</button>

This is an excerpt from the Vue component:

export default {
  name: 'app',
  data () {
    return {
      counter: 1,
      zero: 0,
      posts: [],
      createTitle: '',
      createBody: '',
      visiblePostID: ''

    };
  },

  created () {
    axios.get('http://jsonplaceholder.typicode.com/posts?_start=${this.counter}+${this.zero}&_limit=10').then(response => {
      this.posts = response.data;
    });
  }
};

Answer №1

The initialized function is triggered only during the component's initialization. If you want to send a GET request every time the counter value changes, you should utilize Vue.js watches. You can find more information on this in the following link.

Incorporating this into your sample code:

export default {
  name: 'app',
  data () {
    return {
      counter: 1,
      zero: 0,
      posts: [],
      createTitle: '',
      createBody: '',
      visiblePostID: '',
    }
  },
  watch: {
      counter: function(newValue, oldValue) {
          this.fetchData()
      }
  }
  initialized(){
      this.fetchData()
   },
   methods: {
      fetchData() {
          axios.get(`http://jsonplaceholder.typicode.com/posts?_start=${this.counter}+${this.zero}&_limit=10`).then(response => {
              this.posts = response.data
          })
      }
   }
}

Answer №2

To ensure your counter triggers the appropriate content loading, you must set up a watcher that calls a load method. This way, whenever the counter value changes, the correct posts will be loaded for the paginated results.

export default {
    name: 'app',
    data () {
        return{
            counter: 1,
            ...
        }
    },

    created(){
        this.loadPosts()
    },

    watch: {
        counter(newVal, oldVal){
            this.loadPosts()
        }
    },

    methods: {
        loadPosts(){
            axios.get('http://jsonplaceholder.typicode.com/posts?_start=${this.counter}+${this.zero}&_limit=10')
                .then(response => {
                    this.posts = response.data
                })
        }
    }
}

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

Create a Vue component that integrates with "unpkg"

I am trying to publish my component on unpkg.com. While it is currently available there, it seems to not be working as expected. I have attempted to use the same UMD build for unpkg as I do for my npm build, but it appears that a specific build may be need ...

Updating data of a child component within a Vue parent component

The way I have structured my components involves one component representing an option in a form, with data indicating the currently selected option. A parent component encompasses the entire form, containing both a submit button and a reset button. To keep ...

Challenges Encountered with Random Image Generator in JavaScript

I am encountering an issue with a script that is supposed to change the default images to a random image each time the page is refreshed. However, I keep receiving an error stating that boxID is null. Why is boxID null? <script type="text/javascript" ...

The number field is persisting with its content even after submitting, while the other fields successfully clear up

I am facing an issue where all fields clear up after submission except for the number field. I would appreciate any help on why this is happening and how to fix it. Thank you. Textfield number: const [number, setNumber] = useState(""); const han ...

Displaying a Countdown in a Django Loop: A Step-by-Step

Hey there, I've got a Javascript countdown nested in a Django for loop that's causing some trouble by displaying multiple instances. Currently, only the first countdown works when I click on any of the start buttons. I'd like each button to ...

Encountering issues with pipes and ngModel functionality in Angular causing errors

I have a unique custom dropdown feature that binds the selected dropdown value to an input field in my reactive form using ngModel. I have also implemented a mask on the input fields using a pipe. Here is all the relevant code for this functionality: HTML ...

Adapt vanilla JavaScript code to be compatible with Node.js, MongoDB, and Express framework

In the midst of working on a blog project for my class, I find myself faced with the challenge of integrating Nodejs, Mongo, and Express into our existing setup. Up until now, we have been gradually transitioning to using Express in our application develop ...

Utilizing PHP and JQuery Variables within the CodeIgniter Framework

Can someone please provide guidance on the best approach to handle this particular situation? I currently have a sidebar populated with Li Elements using a foreach loop, which is working perfectly. Each element contains a link that, when clicked, trigger ...

Node.js UDP broadcast to subnet not working properly in Linux

Here is a simplified Node JavaScript code snippet for testing purposes. Click here to view the code on GitHub This code creates a socket for each interface address, calculates the subnet broadcast address, and then sends data every second for 4 seconds t ...

Incorporating numerous dropdown menus to a table filled with data retrieved from a database

I have implemented a dynamic table that adds a new row at the end when a button is clicked. One of the columns in the table contains a dropdown list, and I want this dropdown list to display values from a database. This is how I am constructing my table ...

I am attempting to draw a correlation between two numerical variables

I'm struggling to compare two scores in my game. When they match, I want it to display "You won", but I can't get it to work. I've attempted using the parseInt method and .val method, but no luck so far. var numberFour = Math.floor(Math.ra ...

Is there a formatting error when pulling data from an API using Angular?

The data retrieved from the API follows this format: { “array1”:[ {"id”:1, ”someProperty”:”A"}, {"id":2, "someProperty”:”B”} ], “array2”:[ {"id”:1, ”anotherProperty”:”foo”, ”lastProperty”:”foo2”}, ...

Prevent accordion expansion triggered by the More button click

When the More button is clicked, it should NOT expand and collapse. https://i.sstatic.net/toV1b.gif If the accordion initial state is open, it must stay open even if button is clicked, if initial state is collapsed then after the more button the accordio ...

Top method for transitioning project from Vue2 to Vue3

I am looking to take my project to the next level with vue3 This project is based on symfony and utilizes vue as separate components on the frontend Since I have never tackled a major upgrade before, I'm unsure of the best approach. Any suggestions? ...

Designing an advanced remote upload system using jQuery AJAX and PHP

Currently, I am in the process of developing an image hosting script and everything is going smoothly so far. To enable local uploading with drag & drop + AJAX, I have utilized various plugins which are working perfectly. Now, I am moving on to implementin ...

Guide on triggering a Bootstrap4 popup to appear upon window load in the absence of a set PHP session variable

Is there a way to trigger the opening of a bootstrap4 popup on window load only if the php session variable is not set? session_start(); if(!isset($_SESSION['templateid'])){ // code to open popup } Any suggestions on how to achieve this u ...

Using a combination of look-arounds and tag omission for advanced parsing

I am trying to identify text that is not part of another word (which I have working successfully), but I also want to ensure that the text is not inside an <a> tag. "Java <li>Javascript</li> <a href="">Some Java here</a> more ...

Retrieving user input in React by utilizing the onChange event handler

I have been tasked with creating a Quiz App and I am currently working on building it. The app consists of several components such as "question", "question-list", and "add-question". Within the "add-question" component, there is a form that allows users ...

Add every WebSocket message to a div element in VUE3

Currently, I am facing an issue while attempting to display each trade from Binances Websocket Stream in my VUE3 component. The challenge I'm encountering is that only one line gets rendered and it keeps updating continuously. This is not the desired ...

Securing Codeigniter with CSRF protection while using datatables and an AJAX URL

I am currently utilizing codeigniter and have implemented CSRF protection. We have enabled it using the following configuration: $config['csrf_protection'] = TRUE; For form submission, we are using the following code: `<input type="hidden" ...