jstrother
jstrother

Reputation: 358

mapping an array not returning value

I have an array I'm trying to map values from, but it isn't returning what I need to continue with my project.

The codeblock in question is:

<select
    className={"clubsList"}
    defaultValue={"allClubs"}
    onChange={this.handleClubChange}>
    <option key={"allClubs"} value={"allClubs"}>All Clubs</option>
    {LEAGUE_IDS_NAMES.forEach(league => {
        if (league.id == this.props.fantasyLeagueId) {
            league.clubs.map(club => {
                console.log('club:', club.name);
                return <option key={club.name} value={club.name}>{club.name}</option>;
            });
        }
    })}
</select>

What this is intended to do is display a list of club names. LEAGUE_IDS_NAMES is an imported file that is an array of objects. These objects are soccer leagues, and one of the keys of each league is clubs, which in turn is an array of objects like this:

clubs: [
    {name: 'Club Name1'},
    {name: 'Club Name2'},
    ...
]

I'm using React/Redux to keep a league id in state and then am using that to compare against each league object in the array, checking the id of each. If it matches, it is supposed to give me the return statement. I know that I am accessing the club names properly as the console.log is correctly giving me club names for the league id in state. What it's not doing is giving me the <option> part of it all.

To experiment, I threw a return in front of the league.clubs.name line, but still nothing. The only thing I ever see for this <select> is the "All Clubs" <option>.

Any ideas?

Upvotes: 0

Views: 50

Answers (1)

James
James

Reputation: 82096

The issue is you can’t yield anything from forEach.

Given its only clubs from a specific league you can filter the league and then map the clubs e.g.

const league = LEAGUE_IDS_NAMES.find(l => l.id === this.props.fantasyLeagueId);
return league && league.clubs.map(l => <option key={c.name} value={c.name}>{c.name}</option>)

Since you're following the Redux pattern, you can move the the filtering into a selector.

Upvotes: 2

Related Questions