Home > Enterprise >  Reverse state in redux
Reverse state in redux

Time:11-30

I'm trying to implement sorting functionality in my notes app but have some problems with it. My sort function must just reverse an array of notes but it does not work.

I have a state with notes:

    export const initialState = {
      notes: [
        {
          id: nanoid(),
          text: '',
          date: '',
        },
      ],
    }

Action:

    export const sortNoteAction = ([notes]) => ({
      type: SORT_NOTE,
      payload: [notes],
    })

Reducer:

    export default function notes(state = initialState, { type, payload }) {
      switch (type) {
        case SORT_NOTE: {
          return {
            ...state,
            notes: [payload].reverse(),
          }
        }
        default:
          return state
      }
    }

CodePudding user response:

I think it doesn't work because you are essentially sorting a list with just one item. If you change [notes] to notes (2 occurrences) and [payload] to payload (1 occurrence) it will probably work

CodePudding user response:

Action:

    export const sortNoteAction = (notes=[]) => ({
      type: SORT_NOTE,
      payload: notes,
    })


Reducer:

    export default function notes(state = initialState, action) {
      switch (action.type) {
        case SORT_NOTE: {
          return {
            ...state,
            notes: action.payload.reverse(),
          }
        }
        default:
          return state
      }
    }
  • Related