Skip to content
This repository was archived by the owner on Oct 19, 2018. It is now read-only.
This repository was archived by the owner on Oct 19, 2018. It is now read-only.

Question on how to work with Stores #3

@barriehadfield

Description

@barriehadfield

I am working on the getting-started docs for Stores and Operations and what I have done so far is show a badly designed component which mixes state and business logic and then the tutorial goes on to refactor that.

Here is the example:

class OfferLuckyDip < React::Component::Base

  define_state discount: 30
  define_state lucky_dip_taken: false

  def render
    div do
      h1 {"Your discount is #{state.discount}%"}
      BUTTON { "Lucky Dip" }.on(:click) do
        state.discount! (state.discount + rand(-5..5))
        state.lucky_dip_taken! true
      end unless state.lucky_dip_taken
    end
  end

end

Which we then refactor to this:

class OfferLuckyDip < React::Component::Base

  before_mount do
    @store = Discounter.new
  end

  def render
    div do
      h1 {"Your discount is #{@store.discount}%"}
      BUTTON { "Lucky Dip" }.on(:click) do
        @store.lucky_dip!
      end unless @store.lucky_dip_taken
    end
  end

end

class Discounter < Hyperloop::Store

   state discount: 30, scope: :class, reader: true
   state lucky_dip_taken: false, scope: :class, reader: true

  def lucky_dip!
    mutate.discount( state.discount + rand(-5..5) )
    mutate.lucky_dip_taken true
  end

end

So my questions are:

  • is before_mount do @store = Discounter.new end the best way to create a Store?
  • without wanting to get into Operations yet (that comes later in the tutorial) how do I pass the Store between components or how do I access this Store from other components?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions