Retrieve information from the API every second

In my React Native app, I have a system where customer orders are fetched and displayed on the restaurant side in a specific screen. I'm using the Fetch API to retrieve this data. The workflow is as follows: the customer places an order, which is then stored in the database. On the restaurant side, there's a function:

  const loadData = async () => {
        const response = await fetch(`${API_URL}/getActiveOrders?ID=${id}`);
        const result = await response.json();
        if (result.auth === true) {

                setCurrentOrders(result.data)

        } else {
            setCurrentOrders([])
        }
    }

    useEffect(() => {
        const interval = setInterval(() => {
            loadData();
        }, 1000)
        return () => clearInterval(interval)
    }, [id]);

This function runs every second, making an API call to an Express server to fetch data from the database so that the restaurant can receive orders without delay. However, I've noticed that when the interval is set to 1 second, the app lags due to frequent calls to the server.

My question: Is this the best approach for fetching orders instantly after they're placed by customers? Is there a better way to do this without causing lag, especially with large amounts of data? Will performance be impacted when handling extensive data?

Answer №1

If I had to pinpoint the reason behind the lagging issue, it could be due to a dependency on the useEffect hook. With every state update triggering a new render and running the effect again, an interval is being set up which leads to your app doing this process every second.

To address this, I recommend removing the dependency and executing the effect only once when the component mounts, while also clearing the interval during unmounting.

useEffect(() => {
  const interval = setInterval(() => {
    loadData();
  }, 1000)
  return () => clearInterval(interval)
}, []);

In cases where the id for GET requests updates and you require the latest value, utilizing a React ref to store the id value and incorporating it in the request URL is advisable.

const idRef = React.useRef(id);

useEffect(() => {
  idRef.current = id;
}, [id]);

const loadData = async () => {
  const response = await fetch(`${API_URL}/getActiveOrders?ID=${idRef.current}`);
  const result = await response.json();
  setCurrentOrders(result.auth ? result.data : []);
}

Answer №2

Utilizing websockets would be ideal for your current situation. It is the optimal choice given the circumstances, similar to how a trading website operates.

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

Passing information between VueJs3 components

I have been coding a VueJs3 Project that includes a login system, and it's working perfectly. Now, I want to display the user's logged-in account on the homepage within a div. The message should be: "You are logged in as:" followed by the userna ...

How to efficiently assign a random set of values to a group of players in Javascript/nodejs while ensuring each player does not receive their own inputted value

Within my array, I have stored the following information: players[{nickname: data.player, id: socket.id, data: playerdata}] The playerdata itself is an array playerdata[] In the first value of playerdata, each player has entered a string. (playerindex ...

Identifying Oversized Files on Safari Mobile: A Guide to Detecting Ignored Large Files in

Mobile browsers such as Safari have a tendency to ignore large files when passed in through the <input type="file">. For example, testing with a 10mb image file results in no trigger of any events - no change, no error, nothing. The user action is si ...

The argument provided must be a string comprising of either 12 bytes, a string containing 24 hex characters, or an integer in order to avoid a BSONTypeError

After building a CRUD application using the MERN stack, I attempted to implement a search operation but encountered an error: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer Below is the code ...

The node sends a request to the API to retrieve data, which is then stored in an array. Subsequently, another request is

var UfcAPI = require('ufc-api'); var ufc = new UfcAPI({ version: '3' }); const fighterIdList = []; function fetchFighterIds() { ufc.fighters(function(err, res) { for (let i = 0; i < res.body.length; i++) { ...

Can the color of text be adjusted (to either white or black) based on the background color (in any color and format)?

To achieve a text color that contrasts well with any background, I need to make sure it's either black or white. The background in my app can vary in color and format, so finding the perfect solution has been challenging. Using mix-blend-mode doesn&a ...

Challenges with parsing JSON using jQuery

I am attempting to retrieve data from a page that returns JSON in order to store it in an array. The current code is functional, but I am encountering difficulties when trying to pass the variable (which should contain the content) into the jQuery.parseJSO ...

Validating nested input body objects in NodeJS Express

Struggling with validating nested object request bodies using the "express-validator" package. Imagine a scenario where we are collecting user input with a body structured like this: { "general": { "sessionId": "a2957207-e033-49e7-b9da-1c5f946 ...

Basic use of AJAX for sending the value from jQuery's datepicker

As a novice in JavaScript and AJAX, I'm hoping for your patience as I navigate my way through. In the scope of this project, I am utilizing the CodeIgniter framework. My objective is to implement a datepicker and transmit its value via AJAX. Below is ...

What is the best way to retrieve the full document from mongoDb after a specific document has been updated?

Currently, I am diving into change streams in Node.js (Express.js) and have encountered a tricky situation that has me stuck. I have successfully established a database connection with MongoDB using mongoose async function main() { const uri = process ...

Troubleshooting issue with JQuery AJAX loading Bootstrap Dropdowns

I have a website on GitHub Pages that uses Bootstrap, but I'm having issues with the drop-down menu in the navbar. Sometimes it works and sometimes it doesn't. I am using $("#nav").load("url"); to load the navbar so that I can make changes and ha ...

Altering Collada texture information during the loading process of the .jpg file

Is there a way to modify the texture image data, such as changing the .jpg header text, when loading the .jpg texture in three.js? I am curious if the texture data is accessible somewhere within the code, possibly as a string. How could I go about this? ...

The image tag fails to appear on the browser when the client attempts to access it

Greetings, I am new to web development. I am attempting to create a simple static website that only displays an image in the header tag of an HTML file. The server seems to be working correctly in sending responses to the client, but the problem lies in t ...

Using the $.ajax function with the PUT method and sending an OPTIONS request

Here is my code snippet: function test(segmentId) { var url = "http://...../api/avoidsegments/123456"; $.ajax({ url: url, type: "PUT", contentType: "application/json", data : { "appID": ig_appID, ...

Leveraging functionality from an imported module - NestJS

Currently, I am utilizing a service from a services module within the main scaffolded app controller in NestJS. Although it is functioning as expected - with helloWorldsService.message displaying the appropriate greeting in the @Get method - I can't ...

What is the best way to hand off slots to a descendant component in Vue 3?

Is it possible to have a component within a 'layout' component populate its slots? JS Fiddle <div id="app"> <layout> <page></page> </layout> </div> const app = Vue.createApp({}); ap ...

Struggling with creating and exporting TailwindCSS and NextJS

I'm encountering challenges in constructing and exporting my TailwindCSS and NextJS project. While everything works smoothly when running `npm run dev` with all Tailwind classes functioning properly, I face an issue when executing `npm run build && np ...

The reference to React in useContext is currently undefined

I am currently working on a React App that involves CRUD operations connected to a Rails API. The project structure is as follows: App.js -> UserIndex --> Form --> User -> User My goal is to pass a function from <App /> to its gr ...

Converting URL-esque information to JSON using JavaScript

Does anyone have a solution for converting an array of URL-like data into JSON format? For example, how can we convert the array ["a.b.c.d", "a.c.e.f", "a.b.c.g"] into the following JSON structure: items:{ text: "a", items:[ { ...

Ways to address time discrepancies when the countdown skips ahead with each button click (or initiate a countdown reset upon each click)

Every time I click my countdown button, the timer runs normally once. But if I keep clicking it multiple times, it starts skipping time. Here are my codes: <input type="submit" value="Countdown" id="countdown" onclick="countdown_init()" /> <div i ...