I'm new to React and am trying to build an app which shuffles football players into two teams and am having difficulty with passing data from one component to another.
I have redux and react-redux installed.
In my reducer.js, I take a list of players and shuffle them, adding the shuffled list to state:
const shufflePlayers = (state) => {
return {
...state,
shuffledList: [
...state.playersList.sort(() => Math.random() - 0.5)
]
}
}
Then in 'src/components/DisplayTeams.index.js', I map the 'shuffledList' array to props:
import { connect } from "react-redux";
import DisplayTeams from "./DisplayTeams";
const mapStateToProps = (state) => {
return {
shuffledList: state.shuffledList,
};
};
export default connect(mapStateToProps)(DisplayTeams);
and finally, in 'src/components/DisplayTeams.js', I attempt to render the 'shuffledList' array in a list:
import React from 'react';
import '../../App.css';
const DisplayTeams = ({ shuffledList }) => (
<div>
<ul>
{shuffledList.map((player, index) => (
<li key={index}>{player.name}</li>
))}
</ul>
</div>
);
export default DisplayTeams;
but am getting TypeError: Cannot read property 'map' of undefined, indicating that the 'shuffledList' array is empty or not set at all.
Any help will be much appreciated!!
shuffledList: state.shuffledListdoesn't seem right at all, so yeah, just a problem of looking at how does your state look like.shufflePlayersfunction,shuffledList: [ ...state.playersList.sort() ]mutates the originalstate.playersListarray - you'll want to make a copy before sorting as .sort() mutates the original array:shuffledList: [...state.playersList].sort()