Rookv1.0
РусскийRU

Stores and context

A store such as store Cart() holds state outside a component. EachCart() call makes an instance. A decorator provides that instance down the tree. A context read picks the nearest provider. Each cart shows its own products.

store Cart() {
  public state items string[] = []
  public derived count = items.length

  public func add(name string) {
    items.push(name)
  }
}

dec cartScope(public cart Cart) {}

comp CartContents() {
  const cart = @cartScope.cart

  return <p>{cart.count == 0 ? 'The cart is empty' : `In the cart (${cart.count}): ${cart.items.join(', ')}`}</p>
}

@cartScope(cart)
comp Shop(title string, cart Cart) {
  return <section>
    <h3>{title}</h3>
    <button onClick={cart.add('Mango')}>Add mango</button>
    <button onClick={cart.add('Guava')}>Add guava</button>
    <CartContents />
  </section>
}

document.body.append(<Shop title="Left cart" cart={Cart()} />, <Shop title="Right cart" cart={Cart()} />)

Synchronizing with a server

The component loads the cart in mount. RemoteCart keeps the last list of products confirmed by the server and accepts one request at a time. The preview stores the list in memory. In an app, pass an async function that usesfetch to load the cart with GET or save it with PUT.

interface CartSnapshot {
  items string[]
}

// null loads the cart; a snapshot replaces its contents.
type SyncCart func(?CartSnapshot) Promise<Response>

store RemoteCart(request SyncCart) {
  public state items string[] = []
  public state pending = false
  public state ready = false
  public state problem = ''

  public async func add(name string) {
    if ready {
      await sync({ items:[...items, name] })
    }
  }

  public async func sync(next ?CartSnapshot) {
    if pending {
      return
    }
    pending = true
    problem = ''
    defer {
      pending = false
    }

    const response, networkError = try await request(next)
    if networkError != null {
      problem = 'Could not reach the server.'
      return
    }
    if!response.ok {
      problem = `Server returned HTTP ${response.status}.`
            return
    }

    const body, readError = try await response.text()
    if readError != null {
      problem = 'Could not read the response.'
      return
    }
    const json string = body
    const snapshot, invalid = decode<CartSnapshot>(json)
    if invalid != null {
      problem = 'Invalid cart data.'
      return
    }

    items = snapshot.items
    ready = true
  }
}

// The preview uses an in-memory server with the same response format.
let saved CartSnapshot = { items:['Mango', 'Guava'] }
async func demoRequest(next ?CartSnapshot) Response {
  <-after(250)
  if next != null {
    saved = next
  }
  return new Response(JSON.stringify(saved))
}

comp SyncPanel(cart RemoteCart) {
  mount {
    cart.sync(null)
  }

  return <section>
    <p>{cart.ready ? (cart.items.length == 0 ? 'The cart is empty' : cart.items.join(', ')) : 'Cart not loaded'}</p>
    <button disabled={cart.pending} onClick={cart.sync(null)}>Reload</button>
    <button disabled={cart.pending || !cart.ready} onClick={cart.add('Mango')}>Add mango</button>
    <button disabled={cart.pending || !cart.ready} onClick={cart.add('Guava')}>Add guava</button>
    <p aria-live="polite">{cart.pending ? 'Syncing…' : cart.problem}</p>
  </section>
}

document.body.append(<SyncPanel cart={RemoteCart(demoRequest)} />)

Saving to localStorage

The store reads the product list when it is created and saves it after each change. Add a product and reopen the Run tab to see it restored. A missing or invalid list starts as an empty cart. If saving fails, the component shows the error and keeps the current cart in memory.

func readItems(key string) string[] {
  const saved, readError = try localStorage.getItem(key)
  if readError != null {
    return[]
  }
  if saved == null {
    return[]
  }
  const json string = saved
  const items, invalid = decode<string[]>(json)
  if invalid != null {
    return[]
  }
  return items
}

store SavedCart(key string) {
  public state items = readItems(key)
  public state problem = ''

  func save() {
    try {
      localStorage.setItem(key, JSON.stringify(items))
      problem = ''
    } catch err {
      problem = 'Could not save the cart.'
    }
  }

  public func add(name string) {
    items.push(name)
    save()
  }

  public func clear() {
    items = []
    save()
  }
}

comp CartPanel(cart SavedCart) {
  return <section>
    <p>{cart.items.length == 0 ? 'The cart is empty' : cart.items.join(', ')}</p>
    <button onClick={cart.add('Mango')}>Add mango</button>
    <button onClick={cart.add('Guava')}>Add guava</button>
    <button disabled={cart.items.length == 0} onClick={cart.clear()}>Empty cart</button>
    <p aria-live="polite">{cart.problem}</p>
  </section>
}

document.body.append(<CartPanel cart={SavedCart('rook.guide.stores.cart')} />)

Using a store from a hook

Both forms use the same Cart. Each useCartForm call gets its own draft, while its derived summary reads the shared cart. Add a product in one form to see its name and the updated count in both.

store Cart() {
  public state items string[] = []
  public derived count = items.length

  public func add(name string) {
    items.push(name)
  }
}

hook useCartForm(cart Cart) {
  state draft = ''
  derived summary = cart.count == 0 ? 'The cart is empty' : `In the cart (${cart.count}): ${cart.items.join(', ')}`

    func add() {
    const name = draft.trim()
    if name != '' {
      cart.add(name)
      draft = ''
    }
  }

  return { draft, summary, add }
}

comp CartForm(label string, cart Cart) {
  const form = useCartForm(cart)

  return <section>
    <label>{label} <input bind:value={form.draft} /></label>
    <button onClick={form.add()}>Add</button>
    <p>{form.summary}</p>
  </section>
}

const cart = Cart()
document.body.append(<CartForm label="First form" cart={cart} />, <CartForm label="Second form" cart={cart} />)