Search code examples
reactjsreactjs-fluxflux

Flux: Higher order components to set up store listeners


Following this article Mixins Are Dead. Long Live Composition, I've set up a Pet component listening to pet and owner stores user a higher order component. But how would one pass an owner_id from the pet resource into connectToStores? Is this simply a case where mixins are superior?

Pet = connectToStores(Pet, [PetStore, OwnerStore], (props) => {
  return {
    pet   : PetStore.getOne(props.id),
    owner : OwnerStore.getOne(ownerId), // this should come from pet.owner_id                                        
  };
}); 

Solution

  • Is PetStore.getOne synchronous? Just assign the result to a variable.

    Pet = connectToStores(Pet, [PetStore, OwnerStore], (props) => {
      var pet = PetStore.getOne(props.id);
    
      return {
        pet   : pet,
        owner : OwnerStore.getOne(pet.owner_id),    
      };
    });
    

    If it's not synchronous, your store will need to emit a change event to cause the component to re-render when the pet is available. The component will also somehow need to handle the pet being unavailable.

    Pet = connectToStores(Pet, [PetStore, OwnerStore], (props) => {
      var pet, loaded, owner;
    
      pet = PetStore.getOne(props.id);
      if (pet) {
        loaded = true;
        owner = OwnerStore.getOne(pet.owner_id);
      } else {
        loaded = false;
        owner = null;
      }
    
      return {
        pet    : pet,
        owner  : owner,
        loaded : loaded
      };
    });