Can you give a varied reply without storing any information?

Is there a way to simulate a server endpoint so that each time a user accesses the API, extra properties are added to the response?

For example, initially the endpoint returns:

[{id: 1, price:null}]

Then, with each subsequent call, it adds new information like this: [{id: 1, price: 10}]

I attempted using setTimeout for this purpose, but it didn't work as expected because the frontend is hitting the endpoint every second and re-executing the function.

const data = [/*...*/];

 let loading;
 function load() {
   for(const el of data)
     el.score = Math.random();
 }

 app.get("/api/", (req, res) => {
   if(!loading) loading = setTimeout(load, 5000);

   res.json({ data });
 });

Answer №1

when using the load function asynchronously, keep in mind that the response is not asynchronous. To handle the response properly, place res.json() within the callback function of setTimeout():

setTimeout(() => {
  load();
  res.json(data);
}, 5000);

IMPORTANT: make sure to send data and not {data}

Answer №2

Were you looking for this specific solution? I'm unsure why the 'loading' variable was utilized in your code.

const data = [{ id: 1, price: null }];

let loading;
function load() {
  for (const element of data) element.price = Math.random();
}

app.get("/api", (req, res) => {
  //   if (!loading) loading = setTimeout(load, 5000);
  //   res.json({ data });

  load();
  res.json(data);
});

If there is a delay in the load() function execution, you might want to consider converting it into a promise for better handling.

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

Restrict the display of items in a unordered list element

Below is my code snippet that limits the number of visible list items in a ul: $wnd.$(el) .find('li:gt(9)') .hide() .end() .append( $wnd.$('<li>+More</li>').click( function(){ $wnd.$(this).nextAl ...

Completing Forms Automatically with AngularJS

Hello! I'm just starting out with ng and I need to make an autocomplete textbox that will initiate an AJAX call when the text is changed. The catch is that the minimum length required to trigger the AJAX call is 3 characters. However, once the user en ...

Discord.js reaction event handling

I'm in the process of developing a starboard feature for my bot, and everything is functioning well. However, I am facing an issue where I want the bot to ignore reactions made by the author of the original message. Here is the current code snippet: ...

An issue arising from code in Python, JavaScript, HTML, and CSS

I am currently studying JavaScript and Python and have encountered an issue with my code. I wrote a script that is supposed to create a file and input data into it, but the recv_data function is not functioning correctly - the file is not being created. Ca ...

Typescript error: Unable to instantiate __WEBPACK_IMPORTED_MODULE_1_signature_pad__ as a constructor

Currently, I am working on a project using Angular2 and attempting to incorporate a JS library for signature input from https://github.com/szimek/signature_pad. In my code, I have tried utilizing the library in the following way: // .ts file import * as ...

The Javascript navigate method has detected an incorrect language being used

Currently, I am facing a challenge while developing a React JS website related to the navigator issue. Even though my default browser is Chrome and English is set as the language preference, when I check navigator.language it displays "he-IL" instead of En ...

The instance does not define the property or method "message" but it is being referenced during rendering

** Check out the Screenshot Below:-** https://i.sstatic.net/u2UeW.png Take a look at MessageComposer.vue:- <template> <div class="composer"> <textarea v-model="message" @keydown.enter="send" placeholder="Message..."></textare ...

What is the best way to automatically update a list of posts using vuex?

Currently, I am working on a project that utilizes Laravel and Vuejs to function as a Single Page Application (SPA). Within the admin page where I manage posts, I display a list of posts from the database using Vuex and Axios requests. There is also a butt ...

Choose an option from the dropdown menu to reveal the selected item

Consider a scenario with the following select HTML element: <select id="mySelect"> <option>Apple</option> <option>Orange</option> <option>Pineapple</option> <option>Banana</option> </select& ...

What advantages could learning ReactJS first give me before diving into NextJS?

Just mastered TS and now faced with the decision of choosing a framework. I'm curious why it's recommended to learn ReactJS before NextJS. I've read countless articles advising this, but no one seems to delve into the reasons behind it. Ca ...

Error message: Icons failing to display in conjunction with template output | 404 error code

I'm trying to display icons based on a search, but I keep getting a 404 error for http://localhost:3000/static when I input a value. My current folder structure looks like this: Root directory > Public > Icons and Root directory > index.js. ...

How to trigger a function in JavaScript only once

On my webpage, I added a radio button that allows users to choose between Metric or Imperial units. Below is the code for the event handler: var metricRadio = document.getElementById("metric"); var imperialRadio = document.getElementById("imperial"); met ...

What is the best way to selectively create transparency for a specific color in a three.js canvas?

I'm working with a three.js canvas that I generated using liquidfun.js. However, I'm encountering an issue where the canvas is not transparent. I want to make a specific color in the canvas fully transparent, such as the whitish background. Is t ...

Encountering the "Cannot POST" error when submitting the registration form on a Sequelize-driven web application

After spending a considerable amount of time staring at the code, I'm still unable to figure out why my basic registration form isn't working. The goal is to save user data in a PostgreSQL database, with password encryption using bcrypt. However, ...

The limit of update depth when using useState with an array generated from a map operation

I'm working on a component where I'm creating a list from an array using map. Each li element in the list has a ref attached to it to capture the getBoundingClientRect().x and getBoundingClientRect().y coordinates, which are then stored in a refs ...

Node.js Sequelize QueryExplore the power of Sequelize in Node.js

I'm looking to filter the "incomers" based on age, but all I have in the table is their date of birth. I want to find people within a specific age range, how can I accomplish this? router.post('/', function (req, res, next) { let parame ...

Do you have any tips for locating a misplaced jQuery element?

Currently, I am utilizing jQuery.validate and exploring its "success" option, which allows a function to be executed upon valid input on a form. The function takes an argument named "label," which seems to be a dynamically generated label positioned next t ...

execute the execCommand function following an ajax request

I am currently developing a WYSIWYG editor and encountering an issue with image handling using execCommand. Here is a simplified example of my page structure: <div id="buttons_panel"><input id="img_submit" type="button"/></div> <div ...

Tips for aligning text vertically in flexbox arrangements

As I work on building my portfolio, I have implemented links as buttons using flexbox to make responsiveness easier. The height of these flexboxes is set dynamically using JavaScript with percentages. Despite trying various suggestions, none of them provi ...

Create customized validation decorators in class-validator for TypeScript by overriding the `validationOptions` within the `validator` method

Take a look at the example provided in section Custom validation decorators: // Defining a decorator import { registerDecorator, ValidationOptions, ValidationArguments } from 'class-validator'; export function IsLongerThan(property: string, va ...