'Map function stores the value of the last object in the array to all values
I am getting data from Firestore and using the map function to display all of that data. I am sending one of the arguments within a URL to get an image. I am sending a cryptocurrency pair in a URL to get an image in response. I am also displaying the pair in the table. However, when I send the same symbol in the map function, all of my pairs get the same pair sent in the url, the last pair of the data. To simplify the issue:
Steps:
- Map function to display data
Pair
attribute is sent in the link to get image with every map function (click button to see image)Pair
function also displayed in the table
Result:
- The pair in the table is unique and displaying correctly
- All urls in the map function get the same pair, the pair of the last object.
{data.map((trade) => (
<tr>
<td>
<div style={{ display: "flex" }}>
<img
src={trade.image}
style={{
width: "30px",
height: "30px",
marginTop: "13px",
marginRight: "5px",
}}
alt="btc"
/>
<p className="coin-name">{trade.symbol.baseAsset}</p>
</div>
</td>
{/* This same attribute is getting unique values and it is within the same map function */}
{/* ---------------vvvvvvvvvvvvvvvvvvv------------------------------------------------- */}
<td>{trade.symbol.symbol}</td>
<td>{trade.qty}</td>
<td>{Math.round(trade.multiplier)}x avg volume</td>
<td>{trade.price}</td>
<td>{trade.exchangeDetails.name.toUpperCase()}</td>
<td>{Math.round(trade.tradeValue * 1000) / 1000}</td>
<td>
<div>
<Button
onClick={handleOpen}
style={{ backgroundColor: "#142F37 ", color: "white" }}
>
View Graph
</Button>
<Modal
open={open}
onClose={handleClose}
aria-labelledby="modal-modal-title"
aria-describedby="modal-modal-description"
>
<Box sx={style}>
<img
// This attribute is getting the same pair in every object
// -----------------------------------------------------------------------------------------------vvvvvvvvvvvvvvvvvvv
src={`https://2zpbbz.chart-img.com/v1/tradingview/advanced-chart?symbol=${trade.symbol.symbol}`}
alt="No graph for this pair"
style={{ width: "500px" }}
/>
</Box>
</Modal>
</div>
</td>
</tr>
))}
Solution 1:[1]
Making the modal as a different component and passing URL as a prop to that component did the trick.
Solution 2:[2]
Add return statement after your .map
and move your your url outside and save it in a variable
data.map((trade, i)=>{
let symbol = trade.symbol.symbol;
let url = 'https://...'+ symbol;
return(
<tr>
...
</tr>
)
}
and then pass in the url created to src of the <img src={url} ... />
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Husnain Mehmood |
Solution 2 | Ridwan Ajibola |