Jason Fingar
Jason Fingar

Reputation: 3368

Redux Adding UI properties to state object

Let's say I have an initial state in my redux application that looks like this:

{
    themeParks : []
}

And theme park objects are stored in a MongoDB or wherever like this:

{
    ParkName : "Disney World",
    NumberOfRides : 25
}

My app fetches (via ajax) and displays the theme parks on load, and lets me do CRUD operations to add / remove / edit theme parks.

My question is, what is the best point in the application to merge in new properties that I will need, that are related to UI changes and need to be included in the state? For example, at some point I need to add an "editing" boolean property to each theme park, so they look like this:

{
    ParkName : "Disney World",
    NumberOfRides : 25,
    editing : false
}

This "editing" flag needs to be a property of each theme park object, to provide the ability to have multiple theme parks in an editable state while using the application, is that correct? Obviously I don't want or need to store this flag in my database schema as it only relates to UI operations.

My first guess would be to include such logic within my .then function after successful return of the data, like this, but I'm not sure:

let ajax = new AjaxHanlder();
let promise = ajax.DoGet('/path/to/api-endpoint');
promise.then((themeParks) => {
    themeParks.map((themePark, i) => {
        themePark.editing = false;
    });
    dispatch({type : LOAD_THEME_PARKS, payload : themeParks});
});

Also, is there a convention for providing a definition of the theme park object before it is loaded, since the initial state is an empty array and has no knowledge of it?

Thanks in advance for any insight on this, as I attempt to advance my knowledge of redux design patterns :-)

Upvotes: 0

Views: 74

Answers (1)

Nysor
Nysor

Reputation: 38

I recommend adding the editing property to your LOAD_THEME_PARKS reducer. For example, part of your LOAD_THEME_PARKS reducer could look like:

case LOAD_THEME_PARKS:
    return {
          ...state,
          themeParks: action.payload.map(park => park.editing = false)
    };

Upvotes: 1

Related Questions