Utilizing JavaScript and Ajax to Fetch the Following Page of Tumblr Entries

Working on a React project that involves scraping my Tumlbr blog for photo posts to display on a 'blog' page. Since the tumblr.js package doesn't support in-browser calls and my backend is in Rails, I'm utilizing ajax to accomplish this task. Below is the code snippet I used to fetch the first 20 posts from page 1 of my tumblr:

export const getPosts = () => {
  return (dispatch) => {
    $.ajax({
      url:"https://api.tumblr.com/v2/blog/somewhatadrift.tumblr.com/posts/photo?...&api_key=...",
      type: "GET",
      context: this,
      success: function(result) {
        let posts = result.response.posts.filter(post => post.type === 'photo');
        dispatch(setPosts(posts));
      }
    });
  }
}

The output of this call can be viewed here.

In the Tumlbr API documentation, it mentions that total_posts represents "The total number of posts available for this request, useful for paginating through results," but does not provide a clear example on how to implement pagination.

Answer №1

Sure, I'll do my best to provide an answer.

Here is a rough outline of what you need.

const fetchPosts = () => {
    let limit = 20; // feel free to adjust this value up to 50
    const fetchData = function (offset) {
        $.ajax({
            url: `https://api.tumblr.com/v2/blog/somewhatadrift.tumblr.com/posts?limit=${limit}&offset=${offset}`,
            success(result) {
                let i = 0;
                const totalPosts = result.response.total_posts;
                const postLength = result.response.posts.length;
                while (i < postLength) {
                    // your logic here
                    dispatch(setPosts(posts)); // unsure if this triggers re-render in React
                    i++;
                }
                if (totalPosts >= offset && postLength !== 0) {
                    fetchData(offset + limit);
                }
            }
        });
    };
    fetchData(0);
};

Let's break it down further.

let limit = 20

You can set the limit to any value up to 50. Technically, setting it to 20 is sufficient without including it in the URL.

url: `https://api.tumblr.com/v2/blog/somewhatadrift.tumblr.com/posts?limit=${limit}&offset=${offset}`,

We use template literals for dynamic parameter insertion during each loop iteration.

A counter is established with variable i.

The posts are extracted while i is less than postLength, followed by incrementing i with i++.

If the total post count is equal to or greater than the offset, additional posts exist for retrieval, and the function repeats with an incremented counter: fetchData(offset + limit);

Initially, we call fetchData(0); subsequent runs increment the counter until reaching the condition that verifies total posts against offset plus limit, signaling the end of data retrieval.

UPDATE

For each loop iteration, consider logging offset, i, and other variables to observe looping behavior.

I hope this explanation aids your understanding.

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

Choosing specific anchors based on their corresponding div ids

Just beginning my journey with JS, looking to tackle an issue (I know, everyone says that!). My task is to create a script that can choose an anchor element and inject an <img>. Nested within a div with the id of _nwa_social_logins, there are multipl ...

Is it necessary to have both index.js and Component.js files for a single component in React?

Continuously analyzing various projects, I often come across authors who organize their file structures in ways that are perplexing to me without proper explanation. Take, for instance, a component where there is a folder named Header. Inside this folder, ...

Show all <p> lines in a .txt file in a horizontal format instead of vertical using javascript and jquery

I'm attempting to export the content from a div as a .txt file, but all the paragraphs are displaying side by side. For instance, within the div content, I have the following lines: <div id="content> <p>hello</p> <p>H ...

No information returned when making an ajax request to a controller action in MVC

I am facing an issue with my asp.net mvc application. In the following action, the data I receive is always empty: [HttpPost] public ActionResult Create(MyData myData) { .... // Despite sending data, all attributes are null } The structure of MyData i ...

Crack open a JSON object

I am struggling to parse a JSON object. It seems like the code is not working, can you help me? var mock_data = { "available": [{ "UserID": 7, "UserName": "Manoj", "Language": "Java", "Score": 9, "TimeLimit": 4.0 }, { "UserID ...

Is there a way to prevent the Alt+F4 function from closing tabs in the Internet Explorer browser

Ctrl+W and Alt+F4 can be used to close the IE browser, but I am looking to disable this default action. While I have found a way to handle the Ctrl+W command, I am struggling with disabling the Alt+F4 event. It seems that other Alt+Key events like Alt+En ...

Tips for swapping text with an image or icon during mobile scaling

As a newcomer to this field, I am facing challenges in finding specific answers. My current objective is to convert text labels into images when the viewport shrinks to mobile sizes. The complexity arises from the fact that I am employing Leaflet, a JavaSc ...

Minimize or conceal iframe

This iframe contains a Google form that cannot be edited. I am looking for a way to close or hide this iframe, either through a button, a popup window button, or without any button at all. The $gLink variable holds the Google form link through a PHP sessio ...

Perform ng-repeat on an array containing several other arrays

This is an angularjs function that retrieves specific categories. $scope.getSpecificCat = function(p_cat) { $http.get(url+'getSpecificCatJson/' + p_cat).success(function(data){ $scope.specifics = data; }).error(functi ...

Combining objects in JavaScript

I am currently working on converting the object received from the server into a format compatible with the backend system. I have a received object that looks like this { 'User.permissions.user.view.dashboard': true, 'Admin.permissio ...

How can I most effectively establish defaultValues for react-hook-form in this scenario?

I am working on a static Next.js website with only frontend functionality. In the pages/feedback/[id]/edit.tsx page, I need to dynamically retrieve an id and set default values in a nested FeedbackForm component. export const FeedbackForm = ({ editing }: { ...

Retrieve the HTML content from a WebView

Is there a way to extract only the Table (TagName: tbody) from a specific webpage? The link to the webpage is here: I've been following a tutorial on how to do this at , but I'm running into some issues. Can anyone provide assistance? Here&apos ...

Is there a way to showcase individual components on a single surface one at a time?

Let me try to explain my issue as clearly as possible! I am currently working on a website using React and Material-UI. On one of my pages, I have a Paper component where I want to display different components that I have created, but only one at a time. ...

The jQuery UI Dialog refuses to close

Dealing with a perplexing quandary involving jQuery UI Dialog. The default close button on the dialog doesn't seem to be functioning properly - however, an interesting workaround exists! Intriguingly, when clicking on the adjacent areas of the button, ...

Quickest technique to verify a specific telephone number format

Our task is to identify if a given string matches a specific phone number pattern. This pattern consists of three sets of digits separated by hyphens: ddd-ddd-dddd. The patterns currently being tested are: "012-345-6789" "0124-345-6789" "012-3456-6789" " ...

Just starting out with callback functions (using a callback as an argument)(Javascript)

Hello everyone, I'm a beginner here and I have a question about callback functions. Upon reading about them, I felt like I understood the concept. However, when I attempted to implement one in my code, things didn't go as planned. functio ...

Stop the form from submitting when the enter key is pressed using VueJS and Semantic UI

After spending the past two days searching for a solution to this persistent issue, none of the suggested remedies have proven effective so far. My form's HTML structure is as follows: <form id="quote_form" action="" method="get" class="ui large ...

Exploring and adding elements in a sophisticated array or object through recursive searching

After referring to this plunker https://plnkr.co/edit/CIGAA5BmiKU4hCMsOaIB?p=preview, I now require dynamic array operations. [ { title: 'Menu 1', id :1, hide : true, children: [], }, { title: 'Menu 2', hide : t ...

What is the best way to populate missing days in an array up to the current date that do not already contain the "Present" element?

Consider the array below which contains attendance data for an employee (Retrieved from Mongo using Ajax): [{"_id":"5fcdcd49c3657d1e05b846f5","title":"Present","allDay":true,"start":"2020-11- ...

Utilizing a mustache template to display an image stored in a MongoDB database

I am encountering a problem with displaying the image on my "item.hjs" page. I suspect that the issue lies in the base64 conversion from the database. Here is how I am showing the data from the database using a mustache template: {{#items}} <div clas ...