0

In the state.unsortedAllHighScores there will be an array output, but when I try to get that state and sort that in state.sortedAllHighScores, it stays empty? My expected result would be an array that should be sorted after every dispatch, so when the dispatched is being called, it should output the sorted array. This is a highscore ranking, so you know why I want to have that sort function in here.

const initialState = {
    sortedAllHighScores: [],
    unsortedAllHighScores: []
};

export const game = (state = initialState, action) => {
    switch(action.type) {

case types.HIGH_SCORE: {
            return {
                ...state,
                unsortedAllHighScores: [...state.unsortedAllHighScores, state.updatedCurrentScore],
                sortedAllHighScores: [].concat(state.unsortedAllHighScores).sort((a, b) => {
                    console.log(b - a);
                    return b - a;
                })
            }
        }
     }

2
  • what happens if you just sort it like this [...state.unsortedAllHighScores.sort()] Commented Nov 3, 2019 at 16:19
  • 1. You're trying to use the result of an assignment to uAHS , inside the assignment to sAHS array. 2. You should add state.updateCurrentScore to your initial state to avoid confusion on how that's being set. 3. I'd break up the assignment to unsortedAllHighScores from the HIGH_SCORE action type, maybe something like SET_SCORES, because you have to update the state of unsortedAllHighScores before you can then use it in the sortedAllHighScores state as a sorted value. In short, you're doing way too many things at once and it's yielding confusing bugs. Atomization is your friend. Commented Nov 3, 2019 at 16:55

1 Answer 1

1

Have you ever try like this:

case types.HIGH_SCORE: {
    const tmp = [...state.unsortedAllHighScores, state.updatedCurrentScore]
    return {
        ...state,
        unsortedAllHighScores: tmp,
        sortedAllHighScores: [].concat(tmp).sort((a, b) => {
             console.log(b - a);
             return b - a;
        })
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.