简体   繁体   中英

Update the redux state in the reducer having array of objects

I am new to the react-redux.

I do have an object which is like,

 const initialState = {
        Low: [
            {
                id: 0,
                technologyId: 0,
                technology: '',
                level: 'EASY'
            }
        ],
        Medium: [
            {
                id: 0,
                technologyId: 0,
                technology: '',
                level: 'MEDIUM'
            }
        ],
        High: [
            {
                id: 0,
                technologyId: 0,
                technology: '',
                level: 'TOUGH'
            }
        ]
    }

Now, 

    export default function QuizData(state = initialState, action) {
        switch (action.type) {
            case QUIZ_DATA:
                return {
                    ...state,
                    Low: action.data,
                    error: false,
                } 
            case RESET_SETUP_QUIZ: {
            console.log("intial state is ",  ...state);
            return {
                ...state
            }

Now, here what happens is after some manipulations, this objects gets changes with every key is having some values. like,

{
        Low: [
            {
                id: 0,
                technologyId: 11,
                technology: 'xsxs',
                level: 'EASY'
            }
        ],
        Medium: [
            {
                id: 0,
                technologyId: 22,
                technology: 'swwsw',
                level: 'MEDIUM'
            }
        ],
        High: [
            {
                id: 0,
                technologyId: 110,
                technology: 'xsxsx',
                level: 'TOUGH'
            }
        ]
    }

So, This gets changed.Now, what I want to do is that ,

When user clicks a button that time I want to change this to the initial state.

So that it will not have any values as it should be same as by default.

SO, what I tried it

return {
   initalState
}

But here, initial state is also having the same values.

So, I am not getting a way to make it to the initial level.

Can one help me with this ?

Because you use the original state object and return a modified version of it (ie you do affect your initialState).

You must create a copy of the state in your reducer, for example

case QUIZ_DATA:
  return Object.assign(
    {},
    state,
    {
      Low: action.data,
      error: false
    }
  )
case RESET_SETUP_QUIZ: {
  return Object.assign(
    {},
    state
  )
}

You have dedicated librairies like immutablejs to handle this ( https://redux.js.org/recipes/usingimmutablejs )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM