skip to Main Content

I have an asynchronous GetTags() function that returns a value and the main App() function that represents the React component. I am trying to write the values of an array obtained from an asynchronous function (array) to another array located in App(). All values are present in arrays and work, but only within the "then" block. When I access the "TagList" array after the "then" block, I get an empty array. How can I fix this?

async function GetTags()
{
  let result = ["a", "b", "c"];
  return result;
}

function App() 
{
  var TagList:string[] = []
  const TagItems = GetTags().then(resp => {
    console.log("Response array: " + resp) //it works
    TagList = Array.from(resp);
    console.log("final array:" + TagList); //it also works
  });
  console.log("final: " + TagList); //outputs nothing
}

Declaring an array variable as "var" instead of "let" didn’t help in any way (manipulations with the position of the blocks and variables too).

3

Answers


  1. GetTags returns a promise which resolves asynchronously, which is why you have to use the callback then(). Anything outside of the callback .then will be executed most likely before the GetTags promise resolves which means it still has the initial value var TagList:string[] = [].

    Login or Signup to reply.
  2. I suggest looking into the react useState hook. You could instantiate the variable and callback const [tags, setTags] = useState([]); where tags replaces your TagList. Then where you have TagList = ... you can just call the setTags(<desired value here>);

    Login or Signup to reply.
  3. The reason you are seeing an empty array when you access "TagList" outside of the "then" block is that the "GetTags()" function is asynchronous. When you call "GetTags()", it immediately returns a promise and execution continues. The "then" block is executed only after the promise is resolved, which means that the assignment to "TagList" happens after the console.log statement outside of the "then" block.

    To fix this, you can either move all the code that depends on "TagList" inside the "then" block or use the state in your React component to update the UI when the data is ready. Here’s an example using the state:

    import { useState, useEffect } from 'react';
    
    async function GetTags()
    {
      let result = ["a", "b", "c"];
      return result;
    }
    
    function App() 
    {
      const [tagList, setTagList] = useState<string[]>([]);
    
      useEffect(() => {
        GetTags().then(resp => {
          console.log("Response array: " + resp);
          setTagList(Array.from(resp));
        });
      }, []);
    
      console.log("final: " + tagList);
    
      // render the UI using the tagList state
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search