Leveraging a value from a 'then' block in a function's return statement in Types

Here is a function I have:

function configureClient(): ApolloClient<ApolloCache<any>> {
    let myToken = getOktaToken().then(token => {
        return token
    });

    return new ApolloClient<InMemoryCache>({
        uri: "someUrl",
        cache: new InMemoryCache(),
        headers: {
            someAuth: myToken
        }
    });
}

I need to set someAuth: myToken in the headers of the return block, but I'm unsure how to do this using the then block.

Additionally:

Normally, I would use

let myToken = await getOktaToken()
, however I cannot make the async function configureClient() as the
ApolloClient<ApolloCache<any>>
raises issues with ES3. Would this approach have worked?
Type 'typeof DefaultClient' in not a valid async function return type in ES5/ES3 because it does not refer to a Promise compatible constructor value

Answer №1

When dealing with promises, it's important to remember that they are asynchronous. The callback you pass to then will be evaluated after your function has already returned. One way to handle this is by making the entire configureClient function return a Promise. However, keep in mind that this will require you to adjust how you use it in other parts of your application, since the client will now be initialized asynchronously.

function configureClient(): Promise<ApolloClient<ApolloCache<any>>> {
  return getOktaToken().then(token => {
    return new ApolloClient<InMemoryCache>({
      uri: "someUrl",
      cache: new InMemoryCache(),
      headers: {
        someAuth: token
      }
    });
  });
}

// Alternatively, you can use async/await syntax

async function configureClient(): Promise<ApolloClient<ApolloCache<any>>> {
  const token = await getOktaToken()
  return new ApolloClient<InMemoryCache>({
    uri: "someUrl",
    cache: new InMemoryCache(),
    headers: {
      someAuth: token
    }
  });
}

If you need to wait for the client to be fetched before rendering your app, you can delay the rendering process. Here's an example:



const App = () => {
  const [client, setClient] = useState(null)
  useEffect(() => {
    configureClient().then(setClient)
  }, [])

  if (!client) {
    return null
  }

  return (
    <ApolloProvider client={client}>
      ...
    </ApolloProvider>
  )
}

For fetching headers asynchronously, it's recommended to use apollo-link-context. It's advised to move away from using Apollo Boost and migrate to the latest Apollo Client instead. This allows you to configure links for your client instance and add a Context Link, as demonstrated 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

Stop options from being hidden in a select dropdown using HTML

Can I keep the options visible when a user selects an item in the 'select' dropdown? I want to add more options to the 'select' when the user clicks on the 'op2' item, without closing the list of options. <select> <o ...

Struggling to make fadeIn() function properly in conjunction with addClass

I've been struggling with this issue for quite some time now and I just can't seem to make it work. The JavaScript I'm working on involves using addClass and removeClass to display and hide a submenu element. While the addclass and removeCla ...

Issues with MEAN stack post method not updating database records

I'm having trouble passing data via HTTP post method and seeing the changes reflected in the database. This is the code snippet: addJobList(jobitem) { let headers = new Headers(); headers.append('Content-Type','application/json ...

ExpressJS looping back

After exploring and practicing the creation of Rest APIs with both Loopback and ExpressJS individually, When using Loopback: I found it to be quite time-consuming to go through all the documentation and learn about loopback-specific features. However, i ...

Autocomplete feature is not functioning properly when trying to use JSON input

Currently, I am utilizing the MUI autocomplete component in my project. The situation involves making an API call and populating 'options' and 'value' with the response from the API. Below is the code snippet. // App.js import { useEff ...

Having difficulty with redirecting through angular's routeprovider

Hi there, I'm new to Angular and I'm running into an issue where I can't redirect to the signup.html page when I hit localhost:port/projectname/ Even though I have specified the template URL for signup in app.js, I keep getting a 404 error. ...

The error message "writeUserData is not defined" is indicating that there is an undefined variable in the react code

I'm still learning React and I've been working on a new function: This is my code in summary: class Signup extends Component { constructor(props) { super(props); } componentDidMount() { } writeUserData = (userId, username, email) => ...

Using jQuery to create a dynamically moving div that forms an endless wall

In order to create a continuous wall that pulls text from a database and displays it, I've developed the following code: $(function() { var x = 0; var y = 100.0; var z=0; setInterval(function() { x -= 0.1; y -= 0.1; ...

Error in GraphQL query: specified argument is mandatory, yet not supplied

I recently started learning about graphql and encountered an issue with my query. Here is the code I am using: { product { id } } "message": "Field "product" argument "id" of type "String!" is requir ...

Tips on including a trash can symbol to rows in a bootstrap table using React

I am working on a table that contains various fields, and I want to add a trash icon to each row so that when it is clicked, the specific row is deleted. However, I am encountering an issue where the trash icon is not showing up on the row and I am unable ...

Utilizing Vue.js to dynamically add a class through computed properties

As a beginner in Vue.js, I want to dynamically add or remove classes based on certain conditions. Specifically, I am trying to remove the success class when the total sum exceeds 25, but for some reason the color is not changing as expected. Can anyone p ...

The JavaScript file specified in the script tag's src attribute was successfully downloaded, but it did not execute as expected after being fetched

I've implemented an ajax call using jQuery in the following manner: $.ajax({ type: 'GET', url: 'edit.htm', success: function(data){ container.html(data); }, }); After making the ajax call, the data returned includes s ...

"Utilizing multiple optional parameters in Expressjs can lead to the request handler being

Hey there, I could use a fresh perspective on this issue I'm having. I am attempting to set up a request handler that can accept 0, 1, or 2 parameters like http://localhost:3000/{seed}/{size}. The parameters "seed" and "size" should both be optional. ...

What is the best method for loading a script in a PHP file that is triggered by an Ajax request?

Below is the JavaScript code that I am using: <script> if (str == "") { document.getElementById("txtHint1").innerHTML = ""; return; } else { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, ...

retrieve the webpage hosted on the server

Seeking to develop a website where users can input a website URL and have it loaded from the server hosting the HTML page, rather than from the user's computer as iframe does by default. I've experimented with various techniques but all seem to l ...

What is the best way to sort through received JSON information?

I am attempting to create a simple command that retrieves information from imgur, locates the images, and then randomly selects which photo to display. The issue I am encountering is my inability to filter the responses based on specific criteria. Below is ...

Which is preferable: a tracking pixel or a javascript inclusion?

Currently, I am in the process of developing a tracking system to monitor referrals to our websites on behalf of third-party website owners. This involves placing a cookie when a customer clicks through to our site and then extracting their ID from this co ...

Learning how to manipulate images by rotating, resizing, and zooming from the corners on a canvas

Currently I am in the process of creating a collage application and I'm hoping to incorporate a specific visual effect into my images. Click here for an example. My goal is to be able to rotate and resize the image from a specific point when clickin ...

Exploring Blob functionality in TypeScript?

I defined a global Blob object: declare global { interface Blob { prototype: Blob; new (name: string, url: string): Blob; } } It is functioning correctly in this code snippet: export const blobToFile = (blob: Blob) => { let file: File | n ...

Implementing a Form Submission Using Ajax in jQuery Without Post Method

Hey everyone, I am attempting to use ajax to submit some values without refreshing the page or using $_POST. In the third image, you can see my jquery script. I have tried adding alert('1'); but it doesn't work. Even placing it in the first ...