Display data fetched from concurrent Ajax calls in a React Component

I am currently in the process of converting my original project to Reactjs. Since I am new to this and it's my first application, I could use some guidance on how to effectively implement this in a React-friendly way and enhance both my skills and the demo project.

You can view a live demonstration here.

My goal is to display a name as soon as its Ajax request is completed rather than waiting for all promises to finish.

ListManager.js

import React, { Component } from 'react'
import List from './List'

export class ListManager extends Component {
  constructor (props, context) {
    super(props, context)
    this.state = {finaldata: []}
  }

  componentWillMount () {
    const id = [1, 2, 3, 4, 5]
    this.APIres(id)
  }

  APIres (ids) {
    Promise.all(ids.map(id => fetch('http://api.tvmaze.com/shows/' + id).then(resp => resp.json().then(data => data.name))
    )).then(data => {
      data.sort()
      this.setState({finaldata: Object.assign(this.state.finaldata, data)})
    })
  }

  render () {
    return (
      < div>
        <h3>{this.props.title}< /h3>
        <List data={this.state.finaldata} />
      < /div >
    )
  }
}

List.js

'use strict'
import React, { Component } from 'react'

const ListItem = ({ text }) => <li>{text}</li>

const List = ({ data }) => {
  const listNodes = data.map((value, index) => <ListItem text={value} key={index}></ListItem>)

  return <ul>{listNodes}</ul>
}
export default List

One thing to note: the id array will be included in the URL query like example.com/#/?id=1,2,3,4. I plan to use react-router for this implementation.

Answer №1

there are different methods to handle data fetching

1 using sequence DEMO

all requests start at the same time for performance reasons, but the data will be displayed in order of IDs

  fetchDataWithSequence(ids) {
    ids.map(id => fetch('http://api.tvmaze.com/shows/' + id).then(resp => resp.json()) )
    .reduce((sequence,promise)=>
    sequence.then(()=>promise)
    .then(({name})=>{
        this.setState({finaldata: [...this.state.finaldata, name]});
    }), Promise.resolve());
  }

2 sequence is not guaranteed DEMO

all requests start at the same time for performance reasons, but the data will be displayed based on the order of response received, which may differ from the order of IDs

  fetchDataWithoutSequence(ids) {
    ids.forEach(id => fetch('http://api.tvmaze.com/shows/' + id).then(resp => resp.json())
     .then(({name})=>{
      this.setState({finaldata: [...this.state.finaldata, name]})
    }))
  }

3 sorting before setting state

data will be displayed in the order of responses received, but ordering will be done through sort()

  fetchDataAndSort(ids) {
    ids.forEach(id => fetch('http://api.tvmaze.com/shows/' + id).then(resp => resp.json())
     .then(({name})=>{
      this.setState({finaldata: [...this.state.finaldata, name].sort()})
    }))
  }

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

Working with CodeIgniter and extracting data using an AJAX request

I've been experimenting with this code for a while now and I haven't been able to get it to work. I am working with CodeIgniter framework and when I click the button $('.galName').click(initUpdate);, it calls the following function: fu ...

Dynamic loading of Ajax pages

Include the following HTML in your index.php file: <a class="cart-icon" href="cart"></a> <div class="content"></div> Use Ajax to load content from load-content/cart.php: $(document).ready(function(){ $(document).on('click ...

Attempting to alter an image with a click and then revert it back to its original state

I'm currently working on a feature that toggles an image when a specific class is clicked. The code I have so far successfully switches from 'plus.png' to 'minus.png' upon clicking, but I need it to switch back to 'plus.png&ap ...

Having Trouble with CORS when Sending a POST Request to Next.js 13.4.4 API Endpoint

I am currently using Next.js version 13.4.4 and have set up an endpoint at http://localhost:5000/logout. Within my src/app/logout/route.tsx file, the following code is present: import { NextRequest, NextResponse } from "next/server"; export asyn ...

What could be causing my date variable to reset unexpectedly within my map function?

Currently, I'm utilizing a tutorial to create a custom JavaScript calendar and integrating it into a React project You can find the functional JavaScript version in this jsfiddle import { useState, useRef, useMemo } from 'react' import type ...

What is the process for displaying user input on the console?

How can I ensure that the server is receiving user input? What steps should I take to print this input to the console? Currently, the console.log statement only displays "About to create new room", but I require the user input as well. Client-Side: // C ...

Unlock the power of props variable in css-modules for dynamic className styling!

Would it be feasible to utilize a props variable as a css-modules className in React? // Card.js import styles from "./Card.module.scss" const Card = ({ theme }) => <div className={`${styles.card} ${styles[theme]}`> Card Co ...

Testing abstract class methods in Jest can ensure full coverage

In my project, I have an abstract generic service class. export default abstract class GenericService<Type> implements CrudService<Type> { private readonly modifiedUrl: URL; public constructor(url: string) { this.modifiedUrl = ...

"Learn how to easily send media files stored on your local server via WhatsApp using Twilio with Node.js and Express

Whenever I attempt to send the PDF file created through WhatsApp, an error pops up preventing me from viewing it. easyinvoice.createInvoice(data, function(result) { //The response will contain a base64 encoded PDF file ...

Selenium Scrolling: Improving Web Scraping Efficiency with Incomplete Data Extraction

I have been attempting to extract product data from a website that utilizes JavaScript to dynamically render HTML content. Despite using Selenium, implementing scrolling functionality to reach the end of the page, and allowing time for the page to reload, ...

Quick tutorial on extracting an array of objects in Node.js

I need assistance with creating a simple todo app using React JS and Node. How can I fetch an object array (task list) from Node to React in order to display that list when a button is clicked? const lists =[ {toDo: "learn react"} ] app.post(&apos ...

Using AJAX to submit a PHP form without refreshing the page

Currently, I am facing an issue with my PHP and AJAX code for posting data without redirecting the page. Surprisingly, the script works perfectly on the login page but not on other pages. The main difference I observed is that the login page uses if (empty ...

What is the process for implementing a security rule for sub-maps with unique identifiers in Firebase?

I am looking to implement a security rule ensuring that the quantity of a product cannot go below zero. Client-side request: FirebaseFirestore.instance .collection('$collectionPath') .doc('$uid') .update({'car ...

What sets npm run apart from npm start?

Our repository contains a substantial amount of TypeScript code that we can compile and execute using "npm run dev." This setup enables us to access the test JavaScript code via localhost. However, when examining the code in the Chrome debugger, approxim ...

The Shopify API is experiencing an error due to Cross-Origin Read Blocking (CORB) preventing a cross-origin response from being received

I have developed an embedded app for Shopify admin, but I am encountering an issue when making a call to script_tag.json. The error message I receive is 'Cross-Origin Read Blocking (CORB) blocked cross-origin response'. Below is the code snippet ...

After the installation of Storybook, there is a duplicate identifier error that arises with 'LibraryManagedAttributes'

Upon running the command npx storybook@latest init for setting up Storybook, which results in modifying package.json, I encounter an issue where I cannot run the project using npm due to: Error: node_modules/@types/react-dom/node_modules/@types/re ...

Encountering a TypeScript error while trying to pass the myDecorator function as a decorate prop to React

Encountering a TS error that states: (property) decorate?: ((entry: NodeEntry<Node>) => BaseRange[]) | undefined Type '([node, path]: [node: any, path: any]) => { anchor: { path: any; offset: string | number; }; focus: { path: any; offset: ...

Save the click value for future use

My appointment form is divided into separate panels. At Step 1, if a user clicks on London (#Store1), I want to hide the Sunday and Monday options from the calendar in panel 5. Essentially, I need to save this click event so that when the user reaches th ...

Is it possible to install the lib ldap-client module in node.js?

I'm having trouble installing the lib ldap-client package in Node.js. To try and solve this issue, I consulted the following page: https://github.com/nodejs/node-gyp. In an attempt to fix the problem, I have installed python, node-gyp, and Visual St ...

Issue with passing values through React context

Encountering an issue with the React context method I am attempting to implement a language translation switch in the navbar. Upon selecting a specific language from the dropdown of the switch, I need to pass a value to the rendering page using React conte ...