Guide on displaying paginated data retrieved from an API response in React Native console

After trying several tutorials, I still couldn't resolve my issue.

This is where I am stuck in my code

const [data, setData] = useState([])
    useEffect(() => {
          getData()
          
        }, [])
      
        const getData = async () => {
      
          fetch(`my Api`,{ 
          method: 'post',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          }
        }
          )
            .then((response) => response.json())
            .then((responseJson) => {
              setData(responseJson.result);
              console.log("log for Health professionals =====>", responseJson.result)
              console.log("current_page at:::: =====>", responseJson.result.current_page)

            })
            .catch((error) => {
              console.error(error);
            });
      
        }

    const renderItem = ({item }) => {
        return(
          <View style={styles.itemRow} >
    
            <Text style={{fontSize:20}}>{item.current_page}</Text>
            <Text style={{fontSize:40}}>{item.result.current_page}</Text>
         
          </View>
        )
      } 

  
    return (
        <FlatList
           style={styles.container}
               data={data}
               renderItem={renderItem}
               keyExtractor={(item, index)=>index.toString()}
        />
      
    )
  };

Here is the response from my API };

I attempted to display the data from the API response on my mobile screen using pagination in React Native. Unfortunately, I was unable to see any results. Despite consulting various documentation, I was unable to find a solution.
My goal is to implement pagination with this API response in my React Native project.

Answer №1

Based on your input, it seems like there is an issue with the key being passed to the flatlist. You can try the following code snippet:

const fetchData = async () => {
  
      fetch(`my Api`,{ 
      method: 'post',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    }
      )
        .then((response) => response.json())
        .then((responseJson) => {
          setData([...data, ... responseJson.data]);
           

        })
        .catch((error) => {
          console.error(error);
        });
  
    }


return (
    <FlatList
       style={styles.container}
           data={data}
           renderItem={renderItem}
           keyExtractor={(item, index)=>index.toString()}
    />
  
)


const renderItem = ({item }) => {
    return(
      <View style={styles.itemRow} >

        <Text style={{fontSize:20}}>{item.publisher}</Text>
        <Text style={{fontSize:40}}>{item.short_description}</Text>
     
      </View>
    )
  } 

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

Tips for creating Firestore rules for a one-on-one messaging application

After creating a one to one chat app for a website using Firebase and Firestore, I am now looking to set up the Firebase Firestore rules for the same. The functionality of the app involves checking if the user is [email protected], then retrieving chatids ...

A guide on dynamically loading images based on specified conditions in AngularJS

I am trying to display different images based on a value. If the value is greater than 3.50, image1 should be shown; if it is equal to or less than 3.50, image2 should be shown. I have attempted to write this code but I cannot find where I made a mistake. ...

The useEffect hook is not successfully fetching data from the local db.json file

I'm attempting to emulate a Plant API by utilizing a db.json file (with relative path: src\plant-api\db.json), and passing it from the parent component (ItemList) to its child (Item) but I am facing an issue where no data is being displayed ...

Using Three.js: Cloning Mesh and Material to Easily Toggle Clone Opacity

By using the command Mesh.clone();, it is possible to duplicate the mesh. Upon further investigation, I discovered that both the geometry and material are preserved in the clone. However, my goal is to independently adjust the opacity of each mesh. This le ...

Issue with EaselJS: mouse events are no longer functional

I'm currently working on adding a touch animation using the EaselJs library. Interestingly, when I load an image from a local folder, all mouse events work as expected, such as onPress. However, things take a different turn when I opt to use an imag ...

How to access and utilize parent directive methods effectively in AngularJS

Looking for advice on the best way to utilize parent directive methods in its child directive. Option one: Pass it as a scope parameter in the HTML where you initialize the child directive. Option two: Make the parent directive required and gain ...

What is the optimal strategy for managing multilingual text in a React website?

As I develop a react website with multiple localizations, I am faced with the question of how to best store UI texts for different languages. Currently, I am contemplating two approaches: One option is to store text directly in the UI code, using an objec ...

Display a popup notification when clicking in Angular 2

Can anyone help me with displaying a popup message when I click on the select button that says "you have selected this event"? I am using Angular 2. <button type="button" class="button event-buttons" [disabled]="!owned" style=""(click)="eventSet()"&g ...

AngularJS - Multi-controller Data Calculation

I am currently in the process of developing an Angularjs application. The project is quite extensive and requires segmentation into multiple Controllers to manage effectively. One challenge I am facing is performing calculations across these controllers. ...

"Enhance your gaming experience with Three JS special effects

I'm in the process of creating a multiplayer web game using Three JS. So far, I have successfully implemented the game logic on both client and server sides, mesh imports, animations, skill bars, health bars, and the ability for players to engage in c ...

Revamp your handles using the power of jQuery rotatable!

Greetings! I am currently utilizing a minified plugin created by godswearhats in my project. To activate the plugin, I simply call the following function: $('#em_1').rotatable(); Here is an excerpt of my HTML code: <div class="draggable par ...

What is the rationale behind angular-fullstack's decision to implement both put and patch requests in Express?

I recently stumbled upon an article discussing the distinctions between PUT and PATCH requests (Difference between put and patch). Though I've gained some clarity on the topic, there are still aspects that remain unclear to me. One of my major querie ...

Decode the string containing indices inside square brackets and transform it into a JSON array

I have a collection of strings that contain numbers in brackets like "[4]Motherboard, [25]RAM". Is there a way to convert this string into a JSON array while preserving both the IDs and values? The desired output should look like: {"data":[ {"id":"4","i ...

What is the best way to incorporate a description box for each city on the svg map that appears when you hover your mouse over it?

I am looking to display detailed descriptions for each city in the same consistent location on my map. With multiple pieces of information to include for each city, I want to ensure that the description box is positioned at the bottom of the map. Can any ...

What is the best way to position a tooltip near an element for optimal visibility?

One div is located on the page as follows: <div id="tip"> Text for tip goes here... </div> And another one can be found below: <div class="element"> Text for element goes here... </div> There is also a piece of JavaScript ...

Tips for accessing multiple JSON responses from an array in React Native

Typically, in React Native, I would access the JSON response using responseJson, but how can I access more than one response? The JSON is encoded here in php: Login.php if ($row = mysqli_fetch_array($result)) { $allresults = array( 'Data Match ...

Iterating through a dataset in JavaScript

Trying to find specific information on this particular problem has proven challenging, so I figured I would seek assistance here instead. I have a desire to create an arc between an origin and destination based on given longitude and latitude coordinates. ...

Error: Express is undefined and does not have a property called 'use'

I'm encountering a problem with my express server specifically when I utilize the 'app.use' command. Within my task-routes.js file, the following code is present: import express from 'express'; const router = express.Router(); ...

An assortment of the most similar values from a pair of arrays

I am seeking an algorithm optimization for solving a specific problem that may be challenging to explain. My focus is not on speed or performance, but rather on simplicity and readability of the code. I wonder if someone has a more elegant solution than mi ...

What is the process for converting this code to HTML format?

I am new to programming and I am using an API with node.js to display the result in a browser. The API is working fine with console.log, but I want to render it on the browser instead. I am using Jade template for this purpose. How can I write the code t ...