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

The form submits automatically upon loading the page with empty input fields

I recently created a form on my website located at . Initially, the form functioned correctly and the PHP script executed as expected. However, I am now encountering an issue where every time I load the page, a popup message appears indicating that the for ...

Clone all documents from a NodeJS mongoose collection and transfer them to a different server's database

I need assistance with migrating my database to a new server. My collection consists of approximately 410,000 documents, and I am looking to transfer them in batches of 100 to my new server that runs on mongodb. Below is the code I have written for this ...

The script tags encountered an issue loading the resource with a status code of 404

Currently working on an ASP.NET MVC project and encountered an issue on one of the pages. Here is the code snippet with a script included at the bottom... @model IEnumerable<PixelBox.Dtos.ItemGetDto> @{ ViewBag.Title = "Index"; } <body> ...

Arranging JSON elements according to a separate array in Angular 2 or Node.js

Looking for a solution with optimal performance, I am seeking to achieve the rearrangement of a list using either Angular2 or NodeJS. My input consists of user fruit preferences' IDs {15, 43, 55, 67, 98}; In addition, I have a JSON object containin ...

Can a single controller function in ASP.NET MVC4 be used to send back two arrays to the view?

Continuing from my previous query here, I am working with a model called SchoolTestsPerModulePerStudent which looks like this: public partial class SchoolTestsPerModulePerStudent { public long StudentID { get; set; } public long ModuleID { get; se ...

There seems to be an issue with the functionality of ChartJS when used

Currently working on a project that involves creating a chart using chartjs.org. I have retrieved data from my database in a PHP document and saved it into a JSON file: print json_encode($result->fetch_all()); The resulting data looks like this: [["1 ...

Is it possible to utilize onclick for various table cells in jQuery?

I have a situation where I need to loop through dates and display table content accordingly. Could someone please assist me in figuring out how to do this? index.html.erb <% @batches.each do |batch| %> <tr> **<td class = "pie" id ...

How to customize the center text of Chart.js doughnut chart

I've tried every search I can think of, but still can't find a solution to my problem. I want to customize the text in the middle of my doughnut chart (not tooltips). The chart is created using Chart.js and includes a percentage in the center. E ...

You can easily dismiss the modal by clicking on any part of the screen, not just the button

I have a problem with my current code where I can only close a modal by clicking on a specific button. I want to modify it so that the modal can be closed by clicking anywhere on the screen. Unfortunately, as a JavaScript beginner, integrating new code sni ...

Displaying a timer output in an HTML div every second using PHP

I created a custom PHP countdown timer that displays the remaining time in hours, minutes, and seconds (specifically 3 hours) - named countdown.php. The timer output is displayed within a <div> tag on another page called index.html. Now, I am lookin ...

Unable to direct to the main page in index.js of the next.js application

I have been working on a next.js application and encountered an issue with a component I created called <ButtonGroup>. I added a button with the code <Button href="index">Home</Button> to allow users to navigate back to the home ...

Transforming the MUI CircularProgress into a half circle shape

After utilizing CirculaProgress, I was able to achieve the following: https://i.sstatic.net/Y0Seo.png Is there a simple method to transform it into a semicircle like shown here? https://i.sstatic.net/D8bKu.png ...

Bring in Bootstrap and the Carousel plugin using Webpack Encore

Currently, I am tackling an issue within my Symfony project that involves Webpack Encore and the loading of Bootstrap and the Carousel plugin. The problem may stem from how I import Bootstrap, as it seems to partially work when I import the file like this ...

Processing a JSON array of objects in AngularJS

When using Angular's fromJson function to parse a JSON string, I encountered an issue. If the JSON is a simple array like "[1, 2]", the code works fine. However, I need to work with an array of dictionaries instead. var str = "[{'title' ...

Error occurred when trying to run 'npm run dev' on vite: Unable to access the file "node_modules/react/jsx-dev-runtime.js"

After successfully creating a Vite app, I encountered three errors when trying to run the app with npm run dev: [ERROR] Cannot read file "node_modules/react/jsx-dev-runtime.js": Access is denied. [ERROR] Cannot read file "node_modules/react/index.js": Acc ...

Displaying JavaScript values one by one using a for loop and alert

Having an issue with looping through a JSON array in JavaScript. I am trying to extract only SG_J1001 and SG_LS01, but it's not working as expected. The result is coming out like this [{"regis ....... var item = JSON.stringify(data['code'] ...

Unusual jQuery error notification

Short Receiving Error in syntax, unrecognized expression: [object Object] @ jquery.js:4267 This code snippet is from jQ: Sizzle.error = function( msg ) { throw new Error( "Error in syntax, unrecognized expression: " + msg ); // Line 4267 }; Detaile ...

React: Introducing the latest router feature post-login

I'm facing an issue with the Router in React. After a successful login, I am changing the type state in Redux from 0 to 1. However, when I try to make a switch in my App file, I encounter an error. Warning: [react-router] You cannot change <Router ...

Please do not exceed two words in the input field

I need to restrict the input field to only allow up to two words to be entered. It's not about the number of characters, but rather the number of words. Can this restriction be achieved using jQuery Validation? If not, is there a way to implement it u ...

The webpage becomes unresponsive due to an Ajax request

Creating a generic way to call ajax requests on my webpage has been challenging. I've developed an extension method for calling post requests asynchronously. $.tiqPost = function(action,data,callback) { alert('Posting...'); $.fancyb ...