0

I'm using react-redux to fetch data from MongoDB database and put it into React App.
I've following structure to work upon:

const initialState = {
  Level: [{
    wId: Math.random(),
    Level1: [
      {
       id: Math.random(),
       item1: 'item1',
       item2: 'item2'
      },
      .......
    ],
    Level2: [
      {
       id: Math.random(),
       item1: 'item1',
       item2: 'item2'
      },
      .......
    ]
  }]
}

Redux Function:

export default function (state = initialState, action) {
  switch (action.type) {
    case GET_ITEMS:
      return {
        ...state,
        // what should i write here to get above mentioned state structure
      }
   ..............
}

Note:

  1. Initially Level is empty. So if new data is received in payload then the following structure should be formed.
  2. How to update particular item like item1 at level2

Sample Input:

action.payload = {
    id1: 23234,             // should be assigned in Wid
    ITEM: [                 // Level1
        {
            id2: 89724,       // should be assigned in Level1.id
            i: 'abc',       // should be assigned in Level1.item1
            j: 'xyz'        // should be assigned in Level1.item2
        }
    ]
}
kartik tyagi
  • 6,256
  • 2
  • 14
  • 31

1 Answers1

1

I you dont know how many items you are going to get its would be difficult. One way to work around this issue could compare the previos state with current state and update only necessary part that got changed.

You can use number of libraries or follow any answer in How to determine equality for two JavaScript objects? to compare the objects.

Ideally you would need different actions to update Level, Level ->Level 1 and so on.

Create separate actions for adding levels. Call that action when on user events which add a level to your initial state.

export default function (state = initialState, action) {
  switch (action.type) {
    case GET_ITEMS:
      return {
        ...state,
        // what should i write here to get above mentioned state structure
      }
   case ADD_LEVELS:
      return {
                ...state,
                Level: [...state.Level, action.payload.Level]
             }
}

You can move the id generation logic to the component as it will make your life simpler.

Ganesh chaitanya
  • 638
  • 6
  • 18
  • 1
    yes, number of items is uncertain thats make it difficult for me too. @ganeshchaitanya can you tell me how to change state by comparing prev and current state with following structure? little bit of code will help to understand more clearly. – kartik tyagi Jul 30 '20 at 02:49
  • @kartiktyagi : edited my answer to explain in more detail – Ganesh chaitanya Jul 30 '20 at 13:58