George Avgoustis George Avgoustis - 10 months ago 107
React JSX Question

React and Redux architecture issues

Before reading:

This isnt a matter of non working code but a question on architecture. Also i am not currently using the ReactRedux library as im first trying to understand how the parts work on their own in this test app. Its as short as i could cut it but unfortunately still lengthy, please bear with me

Short Intro

I've got an array of

Bottle
models. Using pseudocode,a bottle is defined like so:

class Bottle{

//members
filledLiters
filledLitersCapacity
otherMember1
otherMember2

//functions
toPostableObject(){

//removes functions by running JSON.
var cloneObj = JSON.parse(JSON.stringify(this));
//removes all members we dont want to post
delete cloneObj["otherMember1"];
}

//other functions
}


I've also got a React component that displays all Bottle items.The component needs to store the previous state of all Bottle items as well ( its for animating, disregard this ).

Redux usage

There are complex operations i need to perform on some of the Bottle items using a helper class like so:

var updated_bottles = BottleHandler.performOperationsOnBottles(bottleIds)
mainStore.dispatch({type:"UPDATED_BOTTLES",updated_bottles:updated_bottles})


I dont want to update the store for every operation as i would like the store to be updated all together at the end in one go. Therefore my BottleReducer looks something like this :

var nextState = Object.assign({}, currentState);
nextState.bottles = action.updated_bottles


Where action.updated_bottles is the final state of bottles after having performed the operations.

The issue

Even though everything works, im suspicious that this is the "wrong mindset" for approaching my architecture. One of the reasons is that to avoid keeping the reference to the bottle objects and mutating the state as im performing the operations, i have to do this ugly thing:

var bottlesCloneArray = mainStore.getState().
bottleReducer.bottles.map(
a => {
var l = Object.assign({}, a);
Object.setPrototypeOf( l, Character.prototype );
return l
}
);


This is because i need a cloned array of objects that still retain their original functions ( meaning they're actual instance clones of the class )

If you can point out the flaw/flaws in my logic i'd be grateful.

P.S: The reason i need to keep "deep clones" of the class instances is so that i can keep the previous state of bottles in my React component for the reason of animating between the two states when an update in render happens.

Answer Source

When dealing with redux architecture it can be extremely useful to keep serialisation and immutability at the forefront of every decision, this can be difficult at first especially when you are very used to OOP

As the store's state is just a JS object it can be tempting to use it to keep track of JS instances of more complex model classes, but instead should be treated more like a DB, where you can serialise a representation of your model to and from it in an immutable manner.

Storing the data representations of your bottles in its most primitive form makes things like persistance to localStorage and rehydration of the store possible for more advanced applications that can then allow server side rendering and maybe offline use, but more importantly it makes it much more predictable and obvious what is happening and changing in your application.

Most redux apps i've seen (mine included) go down the functional route of doing away with model classes altogether and simply performing operations in the reducers directly upon the data - potentially using helpers along the way. A downside to this is that it makes for large complex reducers that lack some context.

However there is a middle ground that is perfectly reasonable if you prefer to have such helpers encapsulated into a Bottle class, but you need to think in terms of a case class, which can be created from and serialised back to the data form, and acts immutably if operated upon

Lets look at how this might work for your Bottle (typescript annotated to help show whats happening)

Bottle case class

interface IBottle {
  name: string,
  filledLitres: number
  capacity: number
}

class Bottle implements IBottle {

  // deserialisable
  static fromJSON(json: IBottle): Bottle {
    return new Bottle(json.name, json.filledLitres, json.capacity)
  }

  constructor(public readonly name: string, 
              public readonly filledLitres: number, 
              public readonly capacity: number) {}

  // can still encapuslate computed properties so that is not needed to be done done manually in the views
  get nameAndSize() {
    return `${this.name}: ${this.capacity} Litres` 
  }

  // note that operations are immutable, they return a new instance with the new state
  fill(litres: number): Bottle {
    return new Bottle(this.name, Math.min(this.filledLitres + litres, this.capacity), this.capacity)
  }

  drink(litres: number): Bottle {
    return new Bottle(this.name, Math.max(this.filledLitres - litres, 0), this.capacity)
  }

  // serialisable
  toJSON(): IBottle {
    return {
      name: this.name,
      filledLitres: this.filledLitres,
      capacity: this.capacity
    }
  }

  // instances can be considered equal if properties are the same, as all are immutable
  equals(bottle: Bottle): boolean {
    return bottle.name === this.name &&
           bottle.filledLitres === this.filledLitres && 
           bottle.capacity === this.capacity
  }

  // cloning is easy as it is immutable
  copy(): Bottle {
    return new Bottle(this.name, this.filledLitres, this.capacity)
  }

}

Store state Notice it contains an array of the data representation rather than the class instance

interface IBottleStore {
  bottles: Array<IBottle>
}

Bottles selector Here we use a selector to extract data from the store and perform transformation into class instances that you can pass to your React component as a prop. If using a lib like reselect this result will be memoized, so your instance references will remain the same until their underlying data in the store has changed. This is important for optimising React using PureComponent, which only compares props by reference.

const bottlesSelector = (state: IBottleStore): Array<Bottle> => state.bottles.map(v => Bottle.fromJSON(v))

Bottles reducer In your reducers you can use the Bottle class as a helper to perform operations, rather than doing everything right here in the reducer directly on the data itself

interface IDrinkAction {
  type: 'drink'
  name: string
  litres: number
}

const bottlesReducer = (state: Array<IBottle>, action: IDrinkAction): Array<IBottle> => {
  switch(action.type) {
    case 'drink': 
      // immutably create an array of class instances from current state
      return state.map(v => Bottle.fromJSON(v)) 
              // find the correct bottle and drink from it (drink returns a new instance of Bottle so is immutable)
              .map((b: Bottle): Bottle => b.name === action.name ? b.drink(action.litres) : b)
                // serialise back to date form to put back in the store
                .map((b: Bottle): IBottle => b.toJSON())
    default:
      return state
  }
}

While this drink/fill example is fairly simplistic, and could be just as easily done in as many lines directly on the data in the reducer, it illustrate's that using case class's to represent the data in more real world terms can still be done, and can make it easier to understand and keep code more organised than having a giant reducer and manually computing properties in views, and as a bonus the Bottle class is also easily testable.

By acting immutably throughout, if designed correctly your React class's previous state will continue to hold a reference to your previous bottles (in their own previous state), so there is no need to somehow track that yourself for doing animations etc

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download