Combining `.then` promises in axios - what's the best approach?

Imagine having a wrapper function for the axios function - something that needs to be used in every ajax query to keep the code DRY. Here is an example:

import axios     from "axios"
import NProgress from "nprogress"

const query = (url, options) => {
  NProgress.start()

  return axios({
    url: url,
    method: options.method || "GET",
    data: options.data || {}
  }).then(() => {
    NProgress.done()
  })
}

export default query

The issue arises when trying to add another .then resolver to the query() function as it does not work. Here is an example:

import query from "./query.js"

query("something", {}).then(() => { console.log("This will never be logged") })

Is there a way to add an additional .then() to the query() function?

Answer №1

Simply provide a response!

const fetchData = (url, options) => {
  LoadingScreen.show()

  return axios({
    url: url,
    method: options.method || "GET",
    data: options.data || {}
  }).then((response) => {
    LoadingScreen.hide()
    return response // modification is made here
  })
}

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

Invoke the parent method within the child application

I have a checkbox on the child app controller. When the user clicks it, I need to call a method from the parent controller: Parent app controller: <div ng-controller="ParentCntr as parentCntr"> <child-app></child-app> </div> C ...

arranging objects based on the distance between them

Here is a JSON array I am working with: var details = [ { 'address':'Pantaloons,701-704, 7th Floor, Skyline Icon Business Park, 86-92 Off A. K. Road,Marol Village, Andheri East,Mumbai, Maharashtra 400059', 'lat':&apos ...

Exploring the functionality of Async Storage in React Native for efficient data saving purposes

I'm completely new to working with Async and async storage. I am a bit lost and unsure of how to proceed, but my main objective is to use setWorkouts() to assign workouts based on the values I retrieve from asyncstorage, and then save these workouts. ...

Transform Json data from JavaScript format to a format that PHP can understand

I have a collection of json files that I need to parse and extract information from in order to store it in a database using PHP. The issue I'm encountering is that these json keys do not have quotes around them, like: [{f:{v:11,ib:5,gh:"res",bfr:7, ...

Unexpected Actions from AJAX response in JSON format

When I make a request to the server and receive an object, it looks like this: $(document).ready(function () { var req= $.getJSON("api/Appointments"); req.done(function (data) { $.each(data, function (key, value) { ...

HTML // jQuery - temporarily mute all audio for 10 seconds after page reload

Is there a way to automatically mute all audio sounds on my website for the first 10 seconds after it is reloaded, and then unmute again? <audio id="musWrited" autoplay> <source src="sound/soundl.mp3" type="audio/mp3" /> // < ...

Include a Class into a label using jQuery

I am having an issue where I need to specifically add the error class to a <label> with the name attribute set to choice_16_0. However, when I try to achieve this using my code, it ends up changing all labels on the page to <label for="choice_16_0 ...

Troubleshooting the lack of updates in a partial view with MS AJAX in ASP.NET MVC

I've implemented a search text box and a button that is meant to display the search results in a partial view using ajax when the button is clicked. Even though I can see data when setting a breakpoint in the partial view, nothing appears on the form. ...

Exploring the Power of jQuery Ajax Requests

Currently, I am making an Ajax call from site.com/users/{username} I need to access the url site.com/account/deleteComment, but when I check in fireBug it seems to be trying to access site.com/users/account/deleteComment Below is the code snippet: $ ...

The useEffect hook is failing to resolve a promise

I have received a response from an API that I need to display. Here is a snippet of the sample response (relevant fields only): [ { ...other fields, "latitude": "33.5682166", "longitude": "73 ...

Angular Oops! We ran into a small hiccup: [$injector:modulerr]

I am facing an issue with an angular js error angular.js:36 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.19/$injector/modulerr?p0=app&p1=Error%3A%20…gleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.19%2Fangular.min.js%3A18%3A139) ...

How to utilize a Multidimensional JSON Array in a jQuery Function

I'm struggling with passing a PHP array to a jQuery function and accessing values from a multidimensional JSON array. When I try to retrieve the value of 'lat' using the code below, I receive an error stating Cannot read property 'lat&a ...

I am encountering an issue with identifying a directory in Node.js

This is my HTML code <div id="done_work_1" class="logo-slide-track"> </div> <script>$.ajax({ url: "/static/home/done/", success: function (data) { $(data).find("a").attr("href&q ...

resetting dropdown selections upon page refresh using jQuery and AJAX

Is there a way to reset or clear the values of two select boxes after refreshing the page in CodeIgniter? Currently, both select boxes retain their values after a refresh. Below is the code I am using: <?php echo form_dropdown('cat_id', $ ...

Ways to include x-api-key in Angular API request headers

I am attempting to include the x-api-key header in the headers, as shown below: service.ts import { Injectable } from '@angular/core'; import { Http, Headers, RequestOptions, Response } from '@angular/http'; import { Observable } from ...

Loading google maps markers dynamically with ajax requests

I'm in the process of plotting around 120 markers on a Google Map by utilizing an ajax populated array containing google.maps.LatLng objects Here is my script <script type ="text/javascript"> $.ajaxSetup({ cache: false }); ...

Creating an AJAX request using JQuery in a JSP page and sending it to a Spring controller

At the moment, I am in the process of creating two distinct Ajax JQueries to transmit data from a Google Maps JavaScript page (Latitude, Longitude, and Address of the location searched by the user) to my controller class. However, I am encountering differe ...

Pressing the "Enter" key will submit the contents of

Hello, I have recently created a new chat box and everything seems to be working fine. However, I am facing an issue with submitting a message when I press enter (to go to the function Kucaj()). Can anyone provide assistance with this problem? I tried ad ...

Setting up Material UI Icons in your React js project

I've been having trouble installing the Material UI Icons package with these commands: npm install @material-ui/icons npm install @material-ui/icons --force npm i @mui/icons-material @mui/material Error messages keep popping up and I can't see ...

Error: The function at() is not recognized in myJson.getTestExecutions.results

When attempting to execute this code on a Jenkins instance running on a Linux machine, I encounter the following error message: "Error performing query: TypeError: data.getTestExecutions.results.at is not a function. However, the code runs without an iss ...