0

I'm trying to follow the instructions found in Cleaner/shorter way to update nested state in Redux? [the accepted answer]

The thing is in my particular case, i have a layer that really depends on which model the user has selected up to that point. My structure:

my structure

Now in my reducer, i've tried (just want to change the favorite leaf to true):

let newStateForFavorites = {...state, models: {
            ...state.models,
            62416: {
                ...state.models.62416,
                details: {
                    ...state.models.62416.details,
                    favorited: true
                }
            }
        }};

Javascript complains. If i try to extract it to a var:

const currentModelToFav = action.payload.model_id;
let newStateForFavorites = {...state, models: {
            ...state.models,
            currentModelToFav: {
                ...state.models.currentModelToFav,
                details: {
                    ...state.models.currentModelToFav.details,
                    favorited: true
                }
            }
        }};

Javascript does not associate the const. And it errors out -currentModelToFav is undefined-

Ideas of what i'm doing wrong? Thanks!

rrubiorr81
  • 285
  • 1
  • 5
  • 15
  • Nested state is generally managed by nested reducers (combined via [`combineReducers`](https://redux.js.org/api-reference/combinereducers)) – Mulan Mar 22 '18 at 20:28
  • @naomik I'm doing that. This is just one of the reducers with form just a part of the stored state.. – rrubiorr81 Mar 22 '18 at 20:36

2 Answers2

5

If you want to use a variable as a property name you'll have to use these constructs:

{[variableName] : value}

and

{propertyName : variable[variableName]}

So, your object literal will become:

const currentModelToFav = action.payload.model_id;
let newStateForFavorites = {...state, models: {
        ...state.models,
       [currentModelToFav]: {
            ...state.models[currentModelToFav],
            details: {
                ...state.models[currentModelToFav].details,
                favorited: true
            }
        }
    }};
Titus
  • 22,031
  • 1
  • 23
  • 33
1

You need to use bracket notation to pull an object key using a variable:

const currentModelToFav = action.payload.model_id;
let newStateForFavorites = {
    ...state, 
    models: {
        ...state.models,
        [currentModelToFav]: {
            ...state.models[currentModelToFav],
            details: {
                ...state.models[currentModelToFav].details,
                favorited: true
            }
        }
    }
};
Chase DeAnda
  • 15,963
  • 3
  • 30
  • 41