2

I use react redux (with immer) to store the options and styles of my app after the initialization. How can I change the update function to update specific styles/options of the app, without changing the other options/styles ?

// reducer.js

export const common = produce((draft, action) => {
  if (!draft) {
    return {
      settings: {},
    };
  }
  switch (action.type) {
    case STORE_WIDGET_SETTINGS:
        draft.settings = action.payload.settings;
        return;

    case UPDATE_WIDGET_SETTINGS:
      draft.settings = action.payload.settings;
      return;

    default:
      return;
  }
});

The update function should only update the options/styles states without changing the current options/styles.

Example: Settings before update:

    options: {
      selector: '#root'
    },
    styles: {
      mainContainer: {
        backgroundColor: 'black',
        color: 'white',
      }
    }

Call update function with option:{selector: '#container'}. The settings should be changed to:

options: {
  selector: '#container'
},
styles: {
  mainContainer: {
    backgroundColor: 'black',
    color: 'white',
  }
}

1 Answer 1

1

To do this manually you'll need to update each branch of your state on top of the existing values. You can do this by spreading the existing values and including the new values.

draft.settings = {
  ...draft.settings, // Spread existing values
  ...action.payload.settings, // Override some values from action
  options: {
   ...draft.settings.options, // Spread existing values
   ...action.payload.settings.options // Override some values from action
  },
  styles: {
   ...draft.styles,
   ...action.payload.styles,
   mainContainer: {
   ...draft.styles.mainContainer,
   ...action.payload.mainContainer
   }
  }
}

Some things you can do to simplify this:

1) Flatten your state structure a bit so there's not so many nested objects. This will make updates easier and you can always re-build structures when you pull them out of the data (i.e. selectors). Something like Normalizr can help you with this: https://github.com/paularmstrong/normalizr

2) Break out a few more action types so that not every update happen in a single UPDATE action. Perhaps UPDATE_MAIN_CONTAINER etc.

3) Consider using something like Ramda's merge function to do this for you: https://ramdajs.com/docs/#merge

Links in this answer:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.