What is the best way to update a specific element within a web page?

My current implementation involves utilizing this code snippet within a functional component :

  return (
    <div style={{ height: "700px", overflow: "auto" }}>
      <InfiniteScroll
        pageStart={0}
        loadMore={FetchUpdates}
        hasMore={hasMore}
        loader={
          <ReactLoading type='spin' color='#000000'  />
        }
        useWindow={false}
      >
        <div key={0}>
          {items.map((data) => (
            <Station data={data} func={props.func} />
          ))}
        </div>
      </InfiniteScroll>
    </div>

In normal situations, everything functions correctly when the FetchUpdates function is triggered. However, things do not work as intended when attempting to refresh the items element from an external source.

setItems([]);

I'm open to any suggestions or ideas for resolving this issue.

Update : I have implemented UseCallback to update values originating from the parent component.

  const UpdateItemsAsync = async () => {
    let items2 = await radioBrowser.Next();
    setItems([...items, ...items2]);
    if (items2.length < 50) {
      setHasMore(false);
    }
    else {
      setHasMore(true);
    }
  };

  const FetchUpdates = useCallback(UpdateItemsAsync, [items]);

And here's a simple method for clearing it:

  if (!radioBrowser.IsLastSearch(filter, fname)) {
    radioBrowser.configureSearch(filter, fname);
    setItems([]);
    setHasMore(true);
  }

Update 2

The complete function:

function RadioStations(props) {
  const [items, setItems] = useState(new Array());
  const [hasMore, setHasMore] = useState(true);
  let { filter, fname } = useParams();
  let radioBrowser = new RadioBrowser();

  if (!radioBrowser.IsLastSearch(filter, fname)) {
    radioBrowser.configureSearch(filter, fname);
    setItems([]);
    setHasMore(true);
  }

  const UpdateItemsAsync = async () => {
    let items2 = await radioBrowser.Next();
    setItems([...items, ...items2]);
    if (items2.length < 50) {
      setHasMore(false);
    }
    else {
      setHasMore(true);
    }
  };

  const FetchUpdates = useCallback(UpdateItemsAsync, [items,radioBrowser]);

  return (
    <div style={{ height: "700px", overflow: "auto" }}>
      <InfiniteScroll
        pageStart={0}
        loadMore={FetchUpdates}
        hasMore={hasMore}
        loader={
          <ReactLoading type='spin' color='#000000'  />
        }
        useWindow={false}
      >
        <div key={0}>
          {items.map((data) => (
            <Station data={data} func={props.func} />
          ))}
        </div>
      </InfiniteScroll>
    </div>
  );
}

Answer №1

To provide a more accurate solution, I would require the complete code structure or a functional example. However, updating your useCallback might be a potential fix for the issue.

In general, it is advisable to include any variables or functions used within `useCallback`, `useEffect`, or `useMemo` as dependencies.

const FetchUpdates = useCallback(async() => {
  let items2 = await radioBrowser.Next();
  setItems([...items, ...items2]);
  if (items2.length < 50) {
    setHasMore(false);
  } else {
    setHasMore(true);
  }
}, [items, radioBrowser]);

Answer №2

I encountered an issue and managed to come up with a solution. Here is the workaround I implemented:

function RadioStations(props) {
  const [items, setItems] = useState(new Array());
  const [hasMore, setHasMore] = useState(true);
 
  let { filter, fname } = useParams();
  let radioBrowser = new RadioBrowser();

  if (!radioBrowser.IsLastSearch(filter, fname)) {
    console.log('ok');
    radioBrowser.configureSearch(filter, fname);
    setItems([]);
    items.length = 0;
    items.init = 1;
    setHasMore(true);
  }

  const FetchUpdates = useCallback(async () => {
    let items2 = await radioBrowser.Next();
    setItems([...items, ...items2]);
    if (items2.length < 50) {
      setHasMore(false);
    }
    else { 
      setHasMore(true);
    }
  }, [items,radioBrowser]);

  return (
    <div style={{ height: "700px", overflow: "auto" }}>
       <InfiniteScroll
        pageStart={0}
        loadMore={FetchUpdates}
        hasMore={hasMore || items.init != undefined}
        loader={
          <ReactLoading type='spin' color='#000000'  />
        }
        useWindow={false}
      >
        <div key={0}>
          {items.map((data) => (
            <Station data={data} func={props.func} key={data.stationuuid}/>
          ))}
        </div>
      </InfiniteScroll>
    </div>
  );
}

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

Finding Location Information Based on Latitude and Longitude Using Jquery

Does anyone know of a reliable solution or Jquery plugin that can provide location details based on latitude and longitude coordinates? I heard about the Google Reverse Location API but hoping for a pre-made option. I'm not sure if there are any free ...

Enhance Component Reusability in React by Utilizing Typescript

As I embark on developing a React application, my primary goal is to keep my code DRY. This project marks my first experience with Typescript, and I am grappling with the challenge of ensuring reusability in my components where JSX remains consistent acros ...

Adjust the image size without losing sharpness

I'm currently working on a web application for Minecraft and I am looking for a way to resize someone's skin without losing quality. I believe javascript might be the solution to this issue. ...

Error: The checkbox was clicked, but an undefined property (includes) cannot be read

Link to live project preview on CodeSandbox Visit the product page with checkbox I have developed a code snippet that allows users to filter products by checking a box labeled "Show Consignment Products Only", displaying only those products with the term ...

"Exploring the process of unsubscribing or disposing of an interval observable based on a certain condition in Angular2 or

I am embarking on the journey into Rx and reactive programming, facing a situation that requires me to continuously monitor a hardware's status by sending a POST request to its REST API every 500ms. The goal is to stop the interval observable once the ...

Transfer a term to a different division - JavaScript Object Model

I am trying to achieve a specific task where I need to move one term under another in SharePoint. However, despite my efforts using JSOM and SharePoint 2013, I have not been able to find a direct method for moving terms. The code snippet I have used below ...

JQuery function fails to execute upon first page load

I am currently facing a situation where I need to wait for a specific image to load before either swapping out its src or showing/hiding the next image. The desired outcome is to display a placeholder image (silhouette) until the main image loads, then hi ...

Tips for improving the speed of loading infinite scroll pages

I am currently working on scraping over 100k rows from the provided URL. The data goes back approximately a month, loading in batches of 7-8 rows at a time. My current approach involves using a macro to scroll down the page slowly, which is effective but ...

Animating the change in Slider value with Material-UI in React

Recently delving into React, I encountered my first challenge that has been consuming my time for hours. I'm working with a Slider component from Material-UI and seeking to animate the value changes. Currently, when clicking on a button, the slider i ...

The custom error page in NextJS is failing to display

In my custom pages/404.ts file, I have coded the following: export default function NotFound() { return <h1>404 - Page Not Found</h1> } Additionally, there is another page that displays a 404 error when the organization is null: import Error ...

Ways to initiate animation using CSS when the page loads

Is there a way to initialize the counter on page load? Even though I was successful in making it start on hover, I couldn't figure out how to make it work when the page loads. Here is the JavaScript code: var root = document.querySelector(':root ...

After being deployed on Vercel, React is mistakenly redirecting to the incorrect file, although it functions properly when

I'm a beginner in JavaScript and I recently created a React project. Everything was working smoothly in local development until I deployed the project on Vercel. The issue is when a user clicks on the "about button," instead of showing 'about.htm ...

Minimize data once more using various key criteria

In my current setup, I have created a view that counts reports for different cities. function (doc) { if(doc.type == "report") { emit(doc.city_name, null); } } Using the _count reduce function, I get the following values: {'key': &a ...

Issue with ReactJS/Next.js: Unable to use CRA Proxy to route API requests to Express server

Currently, I am in the process of upgrading a vanilla React application to utilize Next.js (version 7.0.0). The original app was developed using Create-React-App and leveraged the built-in proxy feature of CRA's server. During development, my React a ...

Reactive DevExpress introduces a unique Custom Paging Panel that enhances user

I am looking to customize my Paging Panel in a unique way: Instead of displaying the options for Rows per page as a select dropdown, I want to show them as buttons; I do not want to show the numbers of rows that are currently being displayed; I may want t ...

Tips for changing the size and color of SVG images in a NextJS application

Looking to customize the color and size of an svg image named "headset.svg". Prior to this, I used next/image: <Image src={'/headset.svg'} alt='logo' width={30} height={30} className='object-contain' /> The s ...

The accumulation of input using setInterval is not effective

I need some help with my code. Please take a look at this link here. I want the input to count up from zero and hide when I click the "change" button. But when I show the input again, I want its value to reset back to zero. Can anyone guide me on how to ...

Tips for customizing the appearance of React-Select

Seeking to customize the border on a react-select element, I attempted using the className prop. However, instead of modifying the border directly, it created a new border wrapper around it. Here is my original code: import React from 'react' im ...

Unable to retrieve the field value from the Json Object

I have a JSON object that I need to parse and display in a data table, but I'm having trouble reading the contents of the object. Here is my JavaScript function: finalGrid: function(data){ console.log("Final Grid"); var strJson = JSON.strin ...

We encountered an error while trying to locate the 'socket.io' view in the views directory

Having an issue with my nodejs server. Check out the code below: server.js global.jQuery = global.$ = require('jquery'); var express = require('express'), path = require('path'), menu = require("./routes/menu"); var ...