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
GetTags
returns apromise
which resolves asynchronously, which is why you have to use the callbackthen()
. Anything outside of the callback.then
will be executed most likely before theGetTags
promise resolves which means it still has the initial valuevar TagList:string[] = []
.I suggest looking into the react useState hook. You could instantiate the variable and callback
const [tags, setTags] = useState([]);
wheretags
replaces yourTagList
. Then where you haveTagList = ...
you can just call thesetTags(<desired value here>);
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: