kartik tyagi
kartik tyagi

Reputation: 7150

how to change initialState in react-redux

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
        }
    ]
}

Upvotes: 0

Views: 58

Answers (1)

Ganesh chaitanya
Ganesh chaitanya

Reputation: 658

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.

Upvotes: 1

Related Questions