I am wanting to display information on my app from two mapped arrays.
{filmWorld.Provider &&
filmWorld.Movies.map((movie, index) => {
return (
<div className="movies" key={index}>
<h3>{movie.Title}</h3>
<img src={movie.Poster} alt={movie.Title} />
<h5>{movie.Actors} </h5>
<h6> Price: ${movie.Price}</h6>
<hr />
</div>
);
})}
This is currently working fine but I'm wanting to have another price displayed from another cinema ideally in the same h6. All the other information is the same.
the other map would be very similar:
{cinemaWorld.Provider &&
cinemaWorld.Movies.map((movie, index) => {
return (
<div className="movies" key={index}>
<h6> Price: ${movie.Price}</h6>
</div>
);
})}
but again i would only need the price from this cinema to be displayed on the same h6 tag. Or would it be more intuitive to take a different approach like merging the variables?
The ideal end result code would return something like this:
return (
<div className="movies" key={index}>
<h3>{movie.Title}</h3>
<img src={movie.Poster} alt={movie.Title} />
<h5>{movie.Actors} </h5>
<h6> FilmWorld Price: ${movie.Price}
CinemaWorld Price: ${movie.Price}</h6>
<hr />
</div>
);
})}
So the page would display the movie name, a picture of the movie poster a list of the actors and a price comparison of the two cinemas showing the movie. I'm storing data from two different apis in these variables.
CodePudding user response:
I'd use a memo hook to create the data structure you want
const movies = useMemo(() => {
if (!filmWorld.Provider) return [];
return filmWorld.Movies.map((movie, index) => ({
...movie,
cinemaWorldPrice: cinemaWorld.Provider && cinemaWorld.Movies[index]?.Price,
}));
}, [filmWorld, cinemaWorld]);
This grabs the corresponding index from cinemaWorld.Movies
(with a condition on cinemaWorld.Provider
).
Now you can just iterate the movies
array
{
movies.map((movie, index) => (
<div className="movies" key={index}>
<h3>{movie.Title}</h3>
<img src={movie.Poster} alt={movie.Title} />
<h5>{movie.Actors} </h5>
<h6>
Price: ${movie.Price}
CinemaWorld Price: ${movie.cinemaWorldPrice}
</h6>
<hr />
</div>
));
}