Inderjit SIngh
Inderjit SIngh

Reputation: 41

Sorting the array of object in reducer state

I want to update the react state using redux but data is not sorting correctly

Original Array

    "sections": [
        {
            "id": 8,
            "user_id": 1,
            "field_type_id": 8,
            "section_id": 3,
            "value": "+96******",
            "type": "phone",
            "url": "tel:",
            "icon": "phone"
        }
     {
            "id": 9,
            "user_id": 1,
            "field_type_id": 8,
            "section_id": 3,
            "value": "[email protected]",
            "type": "email",
            "url": "",
            "icon": "email"
        }
    ]

I am updating the state using this code.

state = { ...state,sections :[ ...state.sections.filter(
                (section) => section.id !== action.payload.section.id
              ) , action.payload.section ]  }
            return state

After updating the array objects are getting reversed

   "sections": [
       {
            "id": 9,
            "user_id": 1,
            "field_type_id": 8,
            "section_id": 3,
            "value": "[email protected]",
            "type": "email",
            "url": "",
            "icon": "email"
        }
        {
            "id": 8,
            "user_id": 1,
            "field_type_id": 8,
            "section_id": 3,
            "value": "+91344******",
            "type": "phone",
            "url": "tel:",
            "icon": "phone"
        }
    ]

How can i stop the array reversing?

Upvotes: 2

Views: 62

Answers (2)

Hafid Denguir
Hafid Denguir

Reputation: 952

You can use one of 2 :

 // filter
  const state = {
    ...state,
    sections: state.sections.filter(
      (section) => section.id !== action.payload.section.id
    ),
  };
  
  // Update
  const state = {
    ...state,
    sections: state.sections.map((section) =>
      section.id !== action.payload.section.id
        ? { ...section, url: 'new Value' }
        : section
    ),
  };

Upvotes: 0

Drew Reese
Drew Reese

Reputation: 202801

If you are simply wanting to update an element at a specific index then just use Array.prototype.map to map the previous array to the next, updating the specific element when it's reached. Array order is maintained.

const nextState = {
  ...state,
  sections: state.sections.map(
    section => section.id === action.payload.section.id
      ? action.payload.section
      : section
  ),
};
return nextState;

Upvotes: 1

Related Questions