Using asynchronous functions in React Native still generates a promise despite the presence of the 'await' keyword

After making an API call, my react-native component is supposed to return some SVG. Despite using an async function with await, the function still returns a promise that has not resolved yet.

I have seen similar questions asked before, but I am puzzled as to why my return statement doesn't return the resolved promise even with 'await' in place.

const getQRCode = async () => {
  try {
       const response = await qrFetch;
       const responseText = await response.text();
      // console.log(responseText)
       return responseText;
   } catch(error){
        console.error(error);
      }
}

const xml = getQRCode()

console.log("--XML DATA HERE--")
console.log(xml)

export default function QRCodeScreen({ navigation }) {
  return (
    <SafeAreaView style={styles.safeAreaContainer}>
      <SvgXml xml={xml} width="100%" height="100%" />;
    </SafeAreaView>
  );
}

Update

I have now wrapped my code in an asynchronous function, but encountered a new error.

async function main(){
  const getQRCode = async () => {
    try {
         const response = await qrFetch;
         const responseText = await response.text();
         return responseText;
     } catch(error){
          console.error(error);
        }
  }
  const xml = await getQRCode()
  return xml
}

export default function QRCodeScreen({ navigation }) {
  return (
    <SafeAreaView style={styles.safeAreaContainer}>
      <SvgXml xml={main()} width="100%" height="100%" />
    </SafeAreaView>
  );
}

Error

TypeError: source.split is not a function. (In 'source.split('\n')', 'source.split' is undefined)

The issue may be related to the react-native-svg package I am using. Checking the type of the 'xml' variable confirms it is indeed a string. I might consider reaching out for help or reporting this on the package's GitHub repository.

Answer №1

A function marked as async will always yield a promise when called.

To extract the value from this promise, you need to use the await keyword:

const data = await fetchData()

Issue

  const QRCodeComponent = ({ navigation }) => {
    const [data, setData] = useState(null)
    
    async function fetchQRData() {
      ...your logic here
      // remove return statement
      // instead, use:
      const fetchedData = await fetchData()

      setData(fetchedData)
    }
    
    useEffect(() => {
      fetchQRData()
    }, [])

  return (
    <SafeAreaView style={styles.container}>
      <SvgXml xml={data} width="100%" height="100%" />
    </SafeAreaView>
  );

}

Answer №2

Here is a solution to try out:


const retrieveQRCode = async () => {
  try {
       const response = await qrFetch;
       const responseText = await response.text();
      // console.log(responseText)
       return responseText;
   } catch(error){
        console.error(error);
      }
}

const xmlData = await retrieveQRCode()

console.log("--XML DATA OUTPUT HERE--")
console.log(xmlData)

export default function DisplayQRCode({ navigation }) {
  return (
    <SafeAreaView style={styles.safeAreaContainer}>
      <SvgXml xml={xmlData} width="100%" height="100%" />
    </SafeAreaView>
  );
}

Note:
Ensure to include ; at the end of each line for consistency. I have omitted the ; after <SvgXML... for you ;)

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

Tips for managing asynchronous REST errors in unit tests with Jest

Below is the code snippet for my Node.js test file. This unit test case is failing, here are the details of the code and error message: jest.unmock('./utils.js'); describe('test', () => { it('test', async (done) => ...

Activate the dialog box exclusively after data has been submitted via the submit button on a form

My goal is to create a data saving functionality with a next button. After filling out the form, clicking on the next button triggers a popup dialog asking, "Do you want to submit your data?" To achieve this, I included the following code in my submit but ...

Having trouble incorporating a JavaScript snippet from Google Trends into an HTML webpage

Hey everyone, I've been trying to incorporate a JavaScript script to display Google Trends on an HTML page. I copied the embed code directly from the first image at and modified it as follows. Unfortunately, it's not working as expected. <ht ...

jQuery Autocomplete with Link Options

Can anyone help me with creating a search function for my charity's internal website? I've managed to get it partially working, but I'm struggling to make the results link to the right places. Below is the code I have so far, including test ...

How can I launch five separate instances of Chrome on a Selenium grid, each with a different URL?

I have a list of URLs saved in a JSON file, structured like this: { "urls": [ "http://www.google.com/", "http://www.stackoverflow.com" ] } Currently, these URLs are being opened sequentially by the Selenium WebDriver JavaScript manager on a ...

Dealing with Challenges in Constructing JQuery URLs

I'm facing an issue with loading a website into a specific div (div.content). The website I'm trying to load requires a login through a POST request. When the javascript attempts to load the site, it recognizes the redirection to the login form ...

Integrating AngularJS code into dynamically generated HTML using JavaScript

I am currently utilizing an outdated version of AngularJS (1.3). I have a page where I need to dynamically display different content based on database values. If the user interacts with the page and changes the database value, I want the displayed content ...

The Kendo UI Grid's cancel function fails to revert back to the original data

I am facing an issue with a kendo grid that is embedded inside a kendo window template. This grid gets its data from another grid on the main UI, following a model hierarchy of Fund -> Currency -> Allocations. The main UI grid displays the entire dataset, ...

How can we leverage Shared and Core modules alongside Feature modules in Angular development?

When developing my Angular application, I have adopted a specific architecture approach and included a shared.module.ts file in the shared folder. While leveraging lazy-loading in my app, I find myself puzzled about the necessary imports, declarations, and ...

Understanding text overflow in JavaScript and jQuery

I am facing an issue where the text in some columns of my table is breaking into two lines. I believe reducing the font size will resolve this problem, but I am unsure about where to start coding for this particular issue. If you have any ideas or sugges ...

Observing the innerHTML of a Vue component

Currently, I am utilizing an npm package called vue3-markdown-it to display markdown within some of my content. When the component renders, I need to access its innerHTML and make customized modifications before displaying it in my div. However, there is ...

Issues arising during the initialization of Tinymce

After setting the editor on the frontend, I encountered an issue with initializing tinymce. Here is my code: <head> <script src="//cdn.tinymce.com/4/tinymce.min.js"></script> </head> <body> <a class=pageedit>Edit< ...

The custom font fails to load on a customized Material UI theme

In my React web application, I tried to implement a custom font by writing the following code: import React, { FunctionComponent } from 'react' import { createMuiTheme, MuiThemeProvider } from '@material-ui/core/styles' import SofiaPro ...

Accessing data points in jQuery

Here is a sample code I'm working with : <script type="text/javascript"> var currentPicture;//default picture var picEL;//the image viewer element jQuery("#backImageShower").hover( function(i) { picEL = j ...

Concealing specific elements in Angular by utilizing ng-class conditions

Here's the code snippet I am currently working with: <tr ng-repeat="version in allVersions" ng-class="{{ version['active'] == 'true' ? 'active' : 'inactive' }}"> </tr> The ng-class is functioning ...

Is there a way to include various reactions at once?

I've been searching everywhere for solutions but I'm stuck on this issue. Here's the scenario I'm dealing with: I need my bot to execute a command that will send an embed to a specific channel accessible only by admins. Done. Fol ...

Error: Cannot iterate over Redux props map as it is not a function

I've encountered an issue while trying to render out a Redux state by mapping through an array of objects. Despite receiving the props successfully, I keep getting an error stating that 'map is not a function'. It seems like the mapping func ...

Changing a file object into an image object in AngularJS

Can a file object be converted to an image object? I am in need of the width and height from the file (which is an image). Here is my code: view: <button id="image_file" class="md-button md-raised md-primary" type="file" ngf-select="uploadFile($file ...

Effective techniques for unit testing in Vue.js

Here's a question that's been on my mind: when it comes to unit testing in Vue.js, there are several different packages available. Vue Test Utils Vue Jest Vue Cypress For enterprise projects, which of these options would be considered best ...

Issue with Node/Express: Middleware addition to router does not function as expected

Here is the configuration of my router: app.get('/getReport', (req, res) => { res.send("This is the report"); }); Initially, this router functions properly and successfully displays the message This is the report in the browser However, ...