Anticipating the completion of a sequence of axios requests

Currently tackling a challenge in my React timesheet application. I am facing an issue while attempting to submit multiple entries simultaneously. Each entry requires its own API call, which is causing some trouble in the process. Here's what I have set up so far within a redux Thunk context:

var foo = new Promise((resolve, reject) =>{
    timesheets.forEach(timeentry => {
        api_function = 'XXXXXX' // string for submitting 1 entry
  
        axios.post(url, api_function);
    }
})

The plan is to execute another call once all entries are posted to refresh the timesheet data displayed on the frontend. However, I've encountered an issue where not all posts go through successfully; only 2-3 at most.

I've conducted some console logging to verify that the forEach loop runs the correct number of times and that the api_function string contains the accurate data during each iteration.

The problem lies in understanding why certain entries post successfully while others do not. It doesn't seem to follow any specific pattern as even seemingly random entries either go through or fail.

If there's a more effective approach to address this issue, suggestions would be greatly appreciated. In essence, seeking a method to carry out a series of POST API calls, ensuring completion before making a GET call to update the data.

Answer №1

The solution lies in using Promise.all()

const bar = Promise.all(timesheets.map(timeentry => {
   api_call = "xxxx"
   return axios.post(endpoint, api_call)
}))

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

Choosing a class using Jquery through a For loop in Javascript

I have a group of images with a class applied to them. I am attempting to create a for loop that will iterate through the elements of this class. In Python, you can use "for element in thing" and I was curious if there is something similar in JavaScript. A ...

I'm completely clueless as to what the issue might be - could it possibly

I need some assistance troubleshooting an issue I'm experiencing. When attempting to load my project in Chrome, all I see is a blank white screen. The code used to be in its own file and should display a cube with the help of jQuery and three.js once ...

Finding the exact x and y coordinates of an object within the camera's frame

I'm currently working on figuring out the exact location (x, y, z coordinates) of an object (a BoxGeometry) in the world in reference to the screen (frustum) rather than the world itself. While the frustum.intersectsObject(…) method provides a Boole ...

Detect the size changes of a React DOM node using hooks

Is it possible to measure a React DOM node during the window resize event? I followed the example provided in the React hooks-faq, but it seems to only work for the initial render. When I tried adding a useEffect to listen for the resize event, the callb ...

What is the best way to visually refresh a polymer element that displays data from a frequently changing URL?

Hey there! I'm currently facing an issue with displaying a polymer element that contains some important information. This element is supposed to appear when I tap on an icon, but for some reason it doesn't show up even after the data has been loa ...

Creating a JavaScript-powered web form that allows users to submit their information without causing the page to refresh

Does anyone know how to use Jquery and AJAX to create an email newsletter subscription form on a website that doesn't refresh the page when the user enters their email address and submits? I would like it to leave a "Thank you" text in the email field ...

Exploring Recursive Types in TypeScript

I'm looking to define a type that can hold either a string or an object containing a string or another object... To achieve this, I came up with the following type definition: type TranslationObject = { [key: string]: string | TranslationObject }; H ...

Having trouble with testing an Angular directive?

This is a snippet from my directive spec file for Angular 6. import { Component, DebugElement, NO_ERRORS_SCHEMA } from '@angular/core'; import { TestBed, ComponentFixture, async } from '@angular/core/testing'; import { By } from ' ...

Display the input in the text box before making a selection from the dropdown menu

Latest Technologies: $(document).ready(function(){ $('#userID').change(function(){ $('#username').val($('#userID option:selected').data('username')); }); }); Coding in HTML: <select class="form- ...

add an image from a URL to a json document

I'm trying to add a picture to each entry in my books.json list. The format of my books.json list is like this: [ {"id": 1,"cover": "link1.jpg","bookTitle": "X", "author": "X"}, ...

Transferring a document using axios to the Laravel framework

I am currently utilizing the Quasar file picker to capture files from users and send them to a Laravel controller using Axios. However, when I send the data to the Laravel controller, I am receiving an empty object. Can someone assist me in resolving this ...

Ensure the dark mode switch CSS remains consistent when navigating to different pages

I have been working on a code to toggle between dark and light mode on a webpage. While it works fine within the current page, the issue arises when I navigate to another page or refresh the current one - the mode resets back to default (light). How can I ...

What causes the off-canvas menu to displace my fixed div when it is opened?

Using the Pushy off-canvas menu from GitHub for my website has been great, but it's causing some trouble with my fixed header. When I scroll down the page, the header sticks perfectly to the top, but once I open the off-canvas menu, the header disappe ...

Is it possible to group an array of objects by a specific element?

Take a look at this example: JsFiddle Query: I'm dealing with the following JSON Array y= [ {"LngTrend":15,"DblValue":10,"DtmStamp":1358226000000}, {"LngTrend":16,"DblValue":92,"DtmStamp":1358226000000}, {"LngTrend":17,"DblValue":45,"DtmSta ...

"Enhance Your Website's User Experience with jQuery Aut

One of the challenges I am facing involves an Ajax call that retrieves a JSON representation of data created using PHP's json_encode method: ["Montérégie","Montréal - North Shore","Montréal - South Shore"] These values are extracted from a &apos ...

Tips for showcasing circles in a non-traditional layout

Is it possible to achieve the layout shown in the image below using CSS? I've tried using shape-outside: circle(); but it's not coming out as expected. Any suggestions on how to accomplish this? <!DOCTYPE html> <html lang="en"> <h ...

Issue with unbinding events in Angular directive persists despite efforts to completely unbind

Our directive features a popup that loads a template with a directive to capture all clicks in the document. When a click is detected, it sends an event to close the popup and unbinds the event on the $document. This directive effectively captures docume ...

When a function reference is utilized, Coffeescript presents an unusual conversion of the try/catch/finally block

I recently wrote a helper function to handle errors, and I'm attempting to pass it as an argument to the catch function within a promise: fetchRecords().then (found) -> $scope.recprds = found; .catch( Session.handleError ) .finally( -> ...

Unable to retrieve value using Meteor findOne query

I am experiencing an issue with a component that has a subscription to items. Upon checking the console, I can see that the item is present within the cursor: console.log(Items.find({key: itemKey}).fetch()); The items collection has been imported correct ...

Ensuring the Correctness of URLs Using Javascript

I have a client-side URL validation code that I am currently using. I am wondering if there is a more efficient way to achieve the same result. My question pertains to the overall approach rather than the specific regex. this.validators.myUrl = function ...