Using async/await keywords in React Native while iterating through an array and calling an API does not result in successful resolution

When attempting to request data from my API in this manner:

export default ({ navigation }) => {
// Call getMovieImages with the id of the likedMovies from the state.likedMovies

const { getMovieImages, state:{ likedMovies }} = useContext(MovieContext);
   likedMovies.map(async (item, index) => {
      const data = await getMovieImages(likedMovies[index]) 
      console.log(data)
   })
   return (
  <SafeAreaView style={styles.container}>
   <Text>You liked {likedMovies.length} movies!</Text>
   <View style={styles.navBar}>
    .
    .
    .
   </View>
  </SafeAreaView>
   )
}

Despite utilizing the async keyword before the map function, I am observing undefined values being logged in the console. Can anyone shed light on why this is happening?

I have confirmed that the likedMovies[index] correctly displays the ids of the liked elements within the array, so there seems to be no issue there either. Should I consider using the .then() statement instead?

Furthermore, all types and API requirements have been validated. Everything appears to align accordingly. Your insights on this matter would be greatly appreciated, thank you.

LikedMovies represents an array of integers, and within this example, getMovieImages dynamically generates API requests based on these integers extracted from the likedMovies array. Despite the successful iteration through the indexes by the map function, getMovieImages fails to resolve, leading to undefined data being logged to the console.

While one possible approach could involve segregating the images field into separate objects for liked and non-liked movie images within the state object, I aim to avoid unnecessary repetition. Therefore, any alternative solutions would be highly valued. Thank you for your attention!

Answer №1

Using async await within a map function call will create a promise for each item in the iteration. To achieve this, you can follow the example below:

const data = Promise.all( favoriteShows.map((item, index) => {
           return fetchShowDetails(favoriteShows[index]) }));

This will result in an array containing responses from each iteration.

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

What is the best way to filter out specific data fields from console.log in JavaScript?

When working with Java, I often use lombok to exclude certain fields from being printed. For instance, the @ToString.Exclude annotation can be used to prevent printing the user token. import lombok.ToString; public class TokenResponse { @ToString.Excl ...

Executing mathematical calculations within a JavaScript object

Can an equation be executed inside an object? For instance: var taxes = { gst: '0.10', }; var prices = { first_key: '437.95', total_key: parseFloat(prices.first_key * taxes.gst).toFixed(2), ....... }, }; Or do I n ...

WordPress header causing issues with Document.write()

I have a JavaScript function that utilizes AJAX to retrieve data from a PHP file. Previously, I utilized document.write(data) to display the retrieved content and it worked smoothly on its own. However, upon incorporating the script into WordPress via hea ...

Tips for extracting HTML text with Python and Selenium

Utilizing Python's Selenium module, I am attempting to extract text and store it in a list or dataframe. Specifically, I am looking to retrieve the text "M" from a class named "flex". Once obtained, I want to input this along with another item into a ...

Manipulating JSON objects within a map using jQuery and Gson

I am working with a Java object that contains several nested object fields with basic fields in them. Here is an example: Template { String name; EmailMessage defaultEmailMessage; } EmailMessage { String emailSubject; String emailBody; } ...

How can I convert the left links in my navigation bar to a CSS drop-down menu to make it more responsive on small screens?

Here is the structure of my HTML (at the top): <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></s ...

Switching between different Vaadin tabs using client-side technology

I am currently working on a project to enhance the navigation experience on a website. To achieve this, I am creating a Silverlight component that will enable users to switch between tabs in a Tabsheet. While exploring the functionalities, I came across an ...

Exploring the use of the "++" operator in Regular

Is there a way to detect the presence of ++, --, // or ** signs in a string? Any help would be greatly appreciated. var str = document.getElementById('screen').innerHTML; var res = str.substring(0, str.length); var patt1 = ++,--,//,**; var resul ...

Does Material-UI MenuItem pass arguments to the onClick handler function?

I am currently working with a search.js file and a search-date.js file. Within the search.js file, there is a container called SearchDate which I render. However, I'm puzzled by the behavior of the MenuItem component when it is clicked. The function ...

Is SWR failing to provide outdated data?

My understanding was that SWR should display the cached data upon page load before refreshing with new information from the API. However, in my Next.js app with a simple API timeout, the "loading" message appears every time due to the 5-second delay I adde ...

Troubleshooting the 'App Already Bootstrapped with this Element' Error in AngularJS

When I try to load my AngularJS app, I encounter the following error: Uncaught Error: [ng:btstrpd] App Already Bootstrapped with this Element '<html lang="en" ng-app="app" class="ng-scope">' I have only placed ng-app once in the html elem ...

Converting and saving geometry in three.js using the toJSON method and BufferGeometryLoader for serialization and deserialization. Transmitting geometries as text

Let me start by saying that I am new to three.js and would like to share my learning journey. My objective was to convert geometry into a format that can be transferred to another web worker (as not all objects can be transferred between workers, only s ...

execute a post request with dynamic data to API using nextjs httpService

I am trying to make a call to an endpoint located at using nestjs. However, I keep encountering the following error message: data 13 - XML tags should be given in the POST variable "data" const { data } = await firstValueFrom( this.httpService .post ...

Issue with applying value changes in Timeout on Angular Material components

I'm currently experimenting with Angular, and I seem to be struggling with displaying a fake progress bar using the "angular/material/progress-bar" component. (https://material.angular.io/components/progress-bar/) In my "app.component.html", I have m ...

Utilizing AJAX in Datatables- Effortlessly sharing a URL link to a designated page

I've recently encountered an issue while using Datatables and AJAX to retrieve data from my Rails server. The problem arises when I try to share a specific page (let's say page 2) with another user who is also using Datatables. Due to the paginat ...

Challenges with JavaScript objects while using d3.js

I have been working on rendering a map using d3 within an HTML page that is running on a django web framework. One of the examples I came across from d3's sample archives can be found at this link: http://bl.ocks.org/NPashaP/a74faf20b492ad377312 Upon ...

It appears that AsyncStorage.getItem() is not functioning as expected

Whenever I attempt to use AsyncStorage.getItem() to assign a value, I encounter difficulties retrieving it afterwards. let tokenData = null; const getData = async () => { let token; try { token = await AsyncStorage.getItem('token'); ...

Unable to pass Ajax value to Laravel controller

Currently, I am facing an issue while trying to retrieve a value from an ajax request in my controller. Although my JavaScript function successfully displays the desired value in an alert, when I attempt to pass this value as data to the controller, it is ...

Adding a fresh item into an element within an array using Javascript

Hello everyone! I've been thinking about how to insert a new element into an existing element in an array. I need to handle collisions in hash maps by inserting the new element at the same index where a previous element was stored. Thanks for your he ...

Adding next-auth middleware on top of nextjs middleware in Nextjs implementation

I am in need of the nextjs middleware to be activated for two distinct paths: Firstly, to serve as a protection against unauthorized access by utilizing next-auth. Secondly, to redirect authorized users from specific pages. For example, if an authorized u ...