I know this has been asked a million times, I have looked at the other answers, but for some reason I just don't get it. Sorry for the repeat. I've been working on this for DAYS
TLDR: How do I correctly pass an array of objects into state?
I have created a React Hook, which is a button, that has an OnClick that fires off an action and reducer.
The reducer logic takes an array taken from state, that splits it into two arrays, and then returns these two arrays. Basically, I have a pool of player objects, and then split them into two teams using very basic team-balancing logic.
When I was writing the reducer logic, I tested it in a separate javascript file and when passing an initial state type object into it I was getting the correct output. (an array of objects)
The idea is that a separate component then lists the name property of each player.
When I click the button I get the error in the title and my state is wiped except for the three states I change. MY redux devtool shows both arrays of players just being [null].
Button Hook Component
import { useDispatch } from "react-redux";
const GenerateTeams = () => {
const dispatch = useDispatch();
function passTeamsIntoState() { //this is the problematic one
dispatch ({
type: "GENERATE_TEAMS",
})
}
const goToPage = () => dispatch({ //this one changes state fine
type: "NAV_TO_GENERATE"
});
const onClick = () => {
passTeamsIntoState();
goToPage();
}
return (
<>
<button
className="doButton"
onClick= { onClick }
>
Generate Teams
</button>
</>
)
}
export default GenerateTeams;
The reducer imports a bunch of functions I've put in separate folders, but it returns when I would have thought it should, ...state, then the props we want changed.
Reducer logic
import setTeamMembers from './setTeamMembers';
import selectedPlayers from './selectedPlayers';
const GenerateTeams = (state) => {
let players = [...state.players];
let teams_size = state.teams_size;
// Select required players and generate two balanced teams
let playerPool = selectedPlayers(teams_size, players);
return setTeamMembers(playerPool);
}
let teams = GenerateTeams();
console.log(teams);
let team_one = [...teams.team_one_players];
let team_two = [...teams.team_two_players];
let setTeamsReducer = (state) => {
return {
...state,
team_one_players: team_one,
team_two_players: team_two,
}
}
export default setTeamsReducer;
The component that is meant to list the players is a Redux class based component:
Component that's trying to read the objects
const PlayersCardT1 = ({team_one_players}) => {
return (
<ul>
{
team_one_players.map(player => (
<li name = { player.name } key = { player } />
))
}
</ul>
)
}
export default PlayersCardT1;
and its index.js file:
import { connect } from 'react-redux';
import Players from './PlayersCardT1';
const mapStateToProps = (state) => {
return {
team_one_players: state.team_one_players,
};
};
export default connect(mapStateToProps)(Players);
Also, Happy new year folks!