I have tried to create a list of 'League' objects from the server, the user can click to create a league successfully, but to join a league the user will need to click the icon and the parameter will need to be sent to the joinLeague() function as the league.leagueId is required to join the league by the API:
LeagueList component:
constructor(props) {
super(props);
this.state = {
leagues: []
};
this.createLeague = this.createLeague.bind(this);
this.joinLeague = this.joinLeague.bind(this);
}
joinLeague() {
const payload = {
"username": localStorage.getItem("username"),
"leagueId":
};
fetch(JOIN_LEAGUE_URL, {
method: 'POST',
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": localStorage.getItem("token")
},
body: JSON.stringify(payload)
})
.then(response => response.json())
.then();
}
render() {
const {leagues} = this.state;
const leagueList = leagues.map(league => {
return <tr key={league.leagueId}>
<td style={{whiteSpace: 'nowrap'}}>{league.leagueCreatorUsername}</td>
<td>{league.playerCount}/10</td>
<td>{league.matchesPerPlayer}</td>
<td>{league.numberOfGamesPlayed}</td>
<td>{league.totalGamesToBePlayed}</td>
<i className="fas fa-plus" onClick={this.joinLeague}></i>
</tr>
});
}
In the joinLeague() function above you can see I am trying to create the payload but I need the leagueId from the as a parameter.
How can I accomplish this? I have tried {this.joinLeague.bind(league)} but it didn't work, thanks.
If you use an arrow function, it should bind itself to the scope (keeping the current value of league)
You could try something like this?
render() {
const {leagues} = this.state;
const leagueList = leagues.map(league => {
return <tr key={league.leagueId}>
<td style={{whiteSpace: 'nowrap'}}>{league.leagueCreatorUsername}</td>
<td>{league.playerCount}/10</td>
<td>{league.matchesPerPlayer}</td>
<td>{league.numberOfGamesPlayed}</td>
<td>{league.totalGamesToBePlayed}</td>
<i className="fas fa-plus" onClick={() => this.joinLeague(league.leagueId)}></i>
</tr>
});
}
joinLeague(leagueId) {
const payload = {
"username": localStorage.getItem("username"),
"leagueId": leagueId
};
fetch(JOIN_LEAGUE_URL, {
...
Here is a link to a minimal example, showing that the leagueId is now available in joinLeague