I am looking to initiate an axios request once the previous one has been completed

I am working on an Axios request to retrieve some data and store it in local storage. My goal is to make another request once the first one is complete, using the response data from the initial request.

this.$http.post("http://localhost:8000/oauth/token", data).then(response => { 
      this.$auth.setToken(
        response.data.access_token,
        response.data.expires_in + Date.now()
      );
    }).then(()=>{
      this.$http.get("user").then(response => {
        this.$auth.setAuthenticatedUser(response.data);
        this.user = response.data;
        this.image = response.data.image;
        this.$bus.$emit('logged_user',response.data);
      });

      this.$http
        .get("http://localhost:8000/api/tpa/provider/status")
        .then(res => {
          localStorage.setItem("tpa_provider", JSON.stringify(res.data));
      });

      this.$bus.$emit('logged_user',this.user);

      if(this.$auth.isAuth()){
        this.$router.push({"name":"home"});
      }

I have also attempted to use async/await but have not been successful in achieving the desired outcome.

Answer №1

Approach 1: Passing the outcome to the next "then" callback using return.

this.$http.post("http://localhost:8000/oauth/token", data).then(response => {
  // ...
  return response;
}).then((myResponse) => {
  console.log('result from first step', myResponse);
  // ...
});

Approach 2: Saving the result of the initial request in a higher-level scope variable.

let myResponse;

this.$http.post("http://localhost:8000/oauth/token", data).then(response => {
  myResponse = response;
  // ...
}).then(() => {
  console.log('result from first step', myResponse);
  // ...
});

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

three.js canvas, sphere rotates gracefully to the right

Trying to get the sphere to turn right at a very slow pace. Here is my source code: I have created a new container with canvas inside, you can view the code below. How can I make the sphere turn slowly? You can also check out my git repository on github: s ...

Encountering Typescript errors when trying to destructure a forEach loop from the output of

There are different types categorized based on mimetypes that I am currently working with. export type MimeType = 'image' | 'application' | 'text'; export type ApplicationMimeType = '.pdf' | '.zip'; expor ...

CSS modal does not extend to the full height of its parent container

I am trying to make the popup modal take up the full height, but it is not happening when there is overflow. The popup appears when the user clicks on a card. Below are images showing how the behavior differs when clicking a card with and without scroll. ...

What is the best way to determine the number of dimensions in a JavaScript array?

Take a look at this array and its corresponding expected output: In Javascript, is it possible to dynamically determine how many levels there are in the array ary? var ary = ["a","b",["c","d"],"e",["f","g",["h","i"],"j"]]; Output: 3 var ary = ["a","b",[" ...

React and Material UI: Ensuring Proper Whitespace Handling in Strings

Exploring the use of Typography component from Material UI (https://material-ui.com/api/typography/) The main objective is to maintain the new lines and spaces in a saved string. For instance, if the string contains leading spaces and new lines, it shoul ...

Is it necessary to encapsulate the last Typsecript export in a module?

I am facing the challenge of exporting multiple models and services within a TypeScript module. Origin models/User.ts import {IModel} from "./IModel"; export interface User extends IModel { // ... } services/UserService.ts import {inject} from & ...

What could be causing my Node.js (Express) application to have a response time of 21000 milliseconds for a simple GET request?

Here is the block of code I am working with: // GET - Default (root) app.get('/', (req, res) => { console.log('GET request to "/"..'); res.header('content-type', 'text/html'); return res.end('&ap ...

Changing an array into an object in JavaScript without rearranging the keys

I have a collection { 1: {id: 1, first: 1, last: 5} 2: {id: 2, first: 6, last: 10} 3: {id: 3, first: 11, last: 15} } My goal is to reverse the order of items without rearranging the keys so that it looks like this: { 1: {id: 3, first: 11, last: 15} 2: { ...

Is it possible to conceal the source code within the dist js file using Vue JS?

I am looking to create a detailed logging page that showcases the logs without revealing the specific type of logging. I want to prevent users from accessing the minified vue JS script and easily reading the logged information. Is there a way to implemen ...

Using JSON.parse to convert a JSON list into a JavaScript array is not functioning correctly

By utilizing this function, I am able to fetch a JSON list: $(document).ready(function () { var idContact = @ViewData["IdPhysique"]; var Url = "/Accueil/DonneListeFonctionContact"; $.getJSON(Url, { IdContact: idContact }, function ...

Determine whether two inputs are identical by comparing them

Currently, I am in the process of creating a form for users to update their passwords. The form includes a field for entering a new password and another field for confirming the new password to ensure it has been entered correctly. However, I am facing so ...

Disabling a specific audio element using its ID

Greetings and thank you for taking the time to read my question. I have encountered an issue while attempting to stop an audio element and I am seeking assistance. I am dynamically creating audio elements with parameters, as shown below. var audio = docum ...

Is there a way to supply a list of HTML elements as an argument to a Closure template function?

Below is the template I am working with, and I am looking to pass a list of HTML elements as a parameter: {template .myTemplate} {@param title: string} {@param? listHtml: list<html>} <ul> {foreach $item in $listHtml} & ...

Is your component failing to re-render after a state change?

I am currently in the process of developing a random quote generator. The main feature is a quote box that showcases quotes along with their respective authors. I have implemented a method that triggers upon button click to randomize the list of quotes and ...

Using the spread operator with setState in React TypeScript

I am currently facing an issue with this particular interface. interface parts { general: boolean, source: boolean, target: boolean } Initially, when I set the state in the Parent component and type it with the defined interface, everything wo ...

Unveiling the hidden: Leveraging Python to extract elements not visible in HTML, yet present in Chrome's "Inspect Element" tool

Hello Python Experts! I'm diving into the world of Python and working on a program to retrieve data from a webpage. If the page returned all the information in its HTML source, there wouldn't be an issue as it's easily viewed in Chrome. Howe ...

Tips for adding animation effects to elements when transitioning to a new page using Vuetify

Is there a way to animate the initial display of a page when navigating to it? Here is the code I am currently working with: https://jsfiddle.net/uLhzqxg9/68/ This is the HTML portion: <div id="app"> <v-app dark> <div class ...

Opening a Material UI dialog results in a change in the style of other components

Whenever I open the Dialog component from a button on the AppBar component, the margin on my navbar elements changes unexpectedly. I have checked the HTML using dev tools and there are no CSS changes on either of the components. Any suggestions on how to p ...

The useEffect hook in ReactJs is triggering multiple times

Encountering challenges while developing an Infinite scroll using ReactJs and Intersection observer API. Upon initial application load, the API gets called twice instead of once. This behavior may be due to strict mode, although not confirmed. Additionall ...

What is the best way to showcase items stored in local storage on a website?

Recently, I designed a website that allows users to search for the weather information of various cities. These searches are stored in an object format like this using localstorage. To showcase this on the website, I have attempted the following: < ...