Search code examples
reactjssetstate

How to update specific key-value pair in a multi-dimensional json array for setState?


Below is my state json array that handles the data and page configuration.

   {
        auth: {
            profile: null,
        },
        model: {
            data: null,
            error: null,
        },
        pageConfig: {
            hasHeader: true,
            loader: {
                isLoaderActive: true,
                message: 'Loading...'    
            },
            alert: {
                type: null,
                message: null
            },
            redirect: {
                url: '/',
                data: null
            },
        }
    };

For now, what's working on my side is updating the model.

this.setState(prevState => ({ ...prevState, model: data }));

Easy because it's only working on a simple array but I would like to ask for guidance on how to update specific key-value pair like the isLoaderActive while maintaining other pairs.

TYIA


Solution

  • Use ES6 spread operator

    const state = {
      auth: {
        profile: null,
      },
      model: {
        data: null,
        error: null,
      },
      pageConfig: {
        hasHeader: true,
        loader: {
          isLoaderActive: true,
          message: 'Loading...'
        },
        alert: {
          type: null,
          message: null
        },
        redirect: {
          url: '/',
          data: null
        },
      }
    };
    
    const newState = {
      ...state,
      pageConfig: {
        ...state.pageConfig,
        loader: {
          ...state.pageConfig.loader,
          isLoaderActive: false
        }
    
      }
    }
    
    console.log(newState)

    Or use Lodash.set

    const state = {
      auth: {
        profile: null,
      },
      model: {
        data: null,
        error: null,
      },
      pageConfig: {
        hasHeader: true,
        loader: {
          isLoaderActive: true,
          message: 'Loading...'
        },
        alert: {
          type: null,
          message: null
        },
        redirect: {
          url: '/',
          data: null
        },
      }
    };
    
    const newState = _.set(state, 'pageConfig.loader.isLoaderActive', false)
    console.log(newState)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>