I want to pass strings from a mapped element to a function that is supposed to trigger on click of said element to then do the post request. This is the function:
const update = () => {
axios.
post("http://localhost:4000/api/albums/favorites", "???")
.then(res => {
console.log(res);
})
}
And this is where my mapped data is:
return(
<Container className="d-flex flex-column py-2" style={{ height: "100vh" }}>
<Form.Control
type="search"
placeholder="Search Songs/Artists"
value={search}
onChange={e => setSearch(e.target.value)}
/>
<div className="flex-grow-1 my-100" style={{ overflowY: "auto" }}>
<div className="d-flex m-2 align-items-center card-body">
{searchResult.map(result => (
<div style={{ cursor: "pointer" }} onClick={update}>
<img key={result.imageUrl} src={result.imageUrl} alt=""/>
{result.artistName} - {result.albumName}
</div>
))}
</div>
</div>
</Container>
);
This is data I got from results of a search bar through api. How should I refer the data in place of??? in the update function? I tried looking for an answer but I probably don't know how to articulate my problem very well.
You can just pass each result to your update
function like this
<div style={{ cursor: "pointer" }} onClick={() => update(result)}>
...
and make your update function to accept an argument that you would use in your axios request
const update = (data) => {
axios.
post("http://localhost:4000/api/albums/favorites", data)
.then(res => {
console.log(res);
})
}
Now each result div when clicked will trigger the update function but bound to its data
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.