Typescript: Using axios to retrieve POST response beyond function boundaries

I've been working on a Typescript function that is supposed to generate and return a token value. Everything seems to be functioning properly, but I'm encountering an issue where the token value is only being logged to the console instead of being returned by the function.

createToken(): string{
    axios.post(BASE_URL, body, { headers })
        .then(async (response) => {
            let responseData = response.data;
            let getToken = JSON.stringify(responseData);
            const obj = JSON.parse(getToken);
         
            //The token value is currently being logged in the console, but how can it be properly returned from this function?
            console.log(obj.access_token);
        })
        .catch(err => {
            console.log(err);
        });
    
    return 'The desired token should be returned here';
}

Answer №1

If you prefer a different approach, you can refer to the initial response

async generateToken(): Promise<string> {
    const { result } = await axios.post(API_URL, requestBody, { headers })
    return result.access_token
}

Alternatively, if you are not keen on using async/await, you could do something like this...

async generateToken(): Promise<string> {
      return axios.post(API_URL, requestBody, { headers })
      .then( (response) => {
      let responseData = response.data;
      let tokenData = JSON.stringify(responseData);
      const parsedObj = JSON.parse(tokenData);
      //THE VALUE HAS BEEN LOGGED TO THE CONSOLE, WHAT IS THE BEST WAY TO RETURN IT??
      console.log(parsedObj.access_token);
      return parsedObj.access_token;
      })
      .catch(error => {
        console.error(error);
      });
  } 

Answer №2

When you call the .then() function, it will execute after the completion of the initial function post. This process is asynchronous and typically occurs after the original function has already finished executing.

To ensure that Javascript waits for this to complete before moving on, consider utilizing the async/await syntax instead.

Answer №3

Due to the asynchronous nature of the createToken function, the token cannot be returned in the callback as it has already completed execution by that point. To address this issue, consider refactoring your function using the async/await syntax to ensure it returns a Promise:

async createToken(): Promise<string> {
    const { data } = await axios.post(BASE_URL, body, { headers })
    return data.access_token
}

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

Displaying and concealing a subcomponent within a parent element for a set duration of time

I have a notification component that is displayed as a child component in the parent component after a button click. It automatically hides after a certain number of seconds. Here is the code I have developed: MyCode Parent component: <button (click)= ...

The expected input should be either an HTMLElement or an SVGElement, but the received input is currently null

Below is the code for a component: function SignUpPage() { return ( <> <h1>Sign Up</h1> <input name="userName" /> </> ); } export default SignUpPage; Testing the component: it("should c ...

What is the best way to extract a specific value from a JSON object?

I'm currently working on building a marketplace using Angular. The main marketplace page is already set up and populated with data from a remote JSON file created with mockapi. However, I've encountered an issue when trying to display a single ra ...

Angular 2 file upload encountering CORS issue leading to 401 unauthorized error

Encountered a "401 Unauthorized" error in Chrome and Firefox while attempting to upload files using angular 2 CLI to an apache2-server with a PHP backend. Despite trying three different node modules, the issue persists from the OPTIONS-preflight stage, ...

Updating the parameters when clicking on each pagination button: A guide

Does anyone have advice on implementing pagination? I am currently working on loading a datatable with a few records initially. Once the page is loaded, I want to be able to click on pagination buttons like next or any pagination buttons to display a new s ...

Encountering difficulties in generating a personalized Angular Element

Currently, I am in the process of developing a custom Component that needs to be registered to a module. Here is how it is being done: app.module.ts import { createCustomElement } from "@angular/elements"; @NgModule({ declarations: [ExtensionCompone ...

Tips for displaying a notification about data filtering and loading using the Async Pipe in Angular

Can someone assist me with this issue? I have a code snippet that retrieves characters from an API and allows me to search for specific characters using input. I am trying to display different messages on my HTML page based on the search results. If no it ...

Troubleshooting TypeScript in Visual Studio Code

Currently, I'm attempting to troubleshoot the TypeScript code below using Visual Studio Code: class Student { fullname : string; constructor(public firstname, public middleinitial, public lastname) { this.fullname = firstname + " " + ...

Struggling to extract specific information from a json array using Angular, my current approach is only retrieving a portion of the required data

My JSON structure is as shown in the image below: https://i.stack.imgur.com/5M6aC.png This is my current approach: createUIListElements(){ xml2js.parseString(this.xml, (err, result) => { console.log(result); this.uiListElement = result[ ...

Trouble displaying data from rest api in Angular Material's mat-table

I've been attempting to incorporate mat-table into my Angular 8 project, but I seem to be missing something. The data from my REST endpoint is showing up fine in the console output. Here's my admin.component.html file: <table mat-table [ ...

How can I retrieve a global variable in Angular that was initialized within an IIFE?

I'm a beginner in Angular, so I ask for your patience. Currently, I am in the process of migrating an app from Asp.net MVC5 to Angular. One of the key functionalities of this application involves connecting to a third-party system by downloading a Jav ...

Unable to access property value following AJAX call

Here is my code snippet: constructor(props: any) { super(props); this.state = { list: [], }; } public componentWillMount() { this.loadData(); } public loadData = () => { axios.get(someURL) .then((response) = ...

Obtaining the status code from an HTTP request in Angular 2

I'm struggling to successfully make an HTTP request and either return the response object or a boolean value. I am having trouble handling errors as my `handleError` function is not functioning properly. This is what my code currently looks like: Th ...

The TypeScript error message reads: "You cannot assign type 'undefined' to type 'ReactElement'."

I'm encountering an error in my react project TypeScript error Argument of type 'ReactNode' is not compatible with parameter of type 'ReactElement<any, string | JSXElementConstructor<any>> | ReactElement<any, string | JSX ...

What imports are needed for utilizing Rx.Observable in Angular 6?

My goal is to incorporate the following code snippet: var map = new google.maps.Map(document.getElementById('map'), { zoom: 4, center: { lat: -25.363, lng: 131.044 } }); var source = Rx.Observable.fromEventPattern( function (han ...

"Facing difficulties in personalizing the PrimeNG Quill Editor within an Angular environment

In my Angular 7 project, I am utilizing the PrimeNG Editor (based on Quill) and I have a need to customize the toolbar. Despite experimenting with various configuration options in both HTML and JavaScript, the only modification I have been able to make is ...

Tips on improving the efficiency of a nested 'for' loop through functional programming

Looking for a way to optimize my function that checks for repeated cell phone numbers in a list. Currently, I am using nested for loops and wondering how I can implement functional programming instead? checkDuplicate(): boolean { for (let i = 0; ...

What is the best way to securely transmit a JWT token from the client side to my API for authentication?

I'm facing the challenge of passing a JWT with various methods like GET, POST, PUT, DELETE from my UI to my API. Thus far, I attempted to build a ReactJS frontend. However, when attempting a request, I encountered: POST http://localhost:4000/book/ ...

Choose the object's property name using TypeScript through an interface

Consider a simplified code snippet like the following: interface MyBase { name: string; } interface MyInterface<T extends MyBase> { base: MyBase; age: number; property: "name" // should be: "string" but only p ...

What is the best way to manage the 'content' attribute in TSX?

I'm currently developing an application that utilizes schema.org. In the code snippet below, you can see how I've implemented it: <span itemProp="priceCurrency" content="EUR">€</span> According to schema.org do ...