I am trying to select homeScore and awayScore from my MatchScoreboard object in MatchState
export const selectScoreboard = (state: MatchState) => state.scoreboard;
export const selectHomeScore = createSelector(selectScoreboard, (scoreboard) => scoreboard.homeScore);
export const selectAwayScore = createSelector(selectScoreboard, (scoreboard) => scoreboard.awayScore);
My state structure:
export interface MatchScoreboard {
awayScore: number;
homeScore: number;
}
export interface MatchState {
scoreboard: MatchScoreboard;
}
export const initialState: MatchState = {
scoreboard: {
awayScore: 0,
homeScore: 0,
}
};
Selectors call
store.pipe(select(selectHomeScore));
store.pipe(select(selectAwayScore));
This appraoch works but it is not clean enough for me
store.pipe(select('matchState', 'scoreboard', 'homeScore'));
store.pipe(select('matchState', 'scoreboard', 'awayScore'));
When I try to use selectors I get errors that homeScore and awayScore are undefined in following lines of code
export const selectHomeScore = createSelector(selectScoreboard, (scoreboard) => scoreboard.homeScore);
export const selectAwayScore = createSelector(selectScoreboard, (scoreboard) => scoreboard.awayScore);
State is changed correctly everything is good except getting data through selectors
As you did with the string selector, you must first select matchState
because scoreboard
exists in matchState
.
export const selectMatchState = (state: GlobalStatate) => state.matchState;
// or
export const selectMatchState = createFeatureSelector('matchState')
Now you can do:
export const selectScoreboard = createSelector(selectMatchState, selectScoreboard)
export const selectHomeScore = createSelector(selectScoreboard, (scoreboard) => scoreboard.homeScore);
export const selectAwayScore = createSelector(selectScoreboard, (scoreboard) => scoreboard.awayScore);