Skip to content
Zenty

Loading, loaded and errors

How Zenty's loading, loaded and error state behave, with async fetch patterns and the error messages for duplicate and missing IDs.

Applies to zenty v1.1.0

Both store types carry the same three fields: loading while something is in flight, loaded once data has arrived, and error with the last message. Zenty sets them for its own actions; around network calls you set loading yourself.

How loading ends(link to this section)

  • setLoading(true) starts it. Zenty never sets it to true on its own.
  • Every write ends it: add, addMany, update, updateMany, delete, deleteMany, replaceAll, clear and, on entity stores, set and update.
  • setError('…') ends it. setError(null) keeps it, so you can clear an old error at the start of a request without hiding the spinner.

Loading data from an API(link to this section)

Zenty doesn't fetch. You call your API and hand the result to the store. Because writes and errors end loading, there is no finally block to forget:

stores/products.ts
import { createEntitiesStore } from 'zenty'

type Product = { id: string; name: string; price?: number }

export const useProducts = createEntitiesStore<Product>()

const message = (error: unknown) => (error instanceof Error ? error.message : String(error))

export async function fetchProducts() {
  const { setLoading, setError, replaceAll } = useProducts.getState()

  setError(null) // clears an old error, keeps loading as it is
  setLoading(true)
  try {
    const response = await fetch('/api/products')
    if (!response.ok) throw new Error(`HTTP ${response.status}`)
    replaceAll(await response.json()) // ends loading
  } catch (error) {
    setError(message(error)) // ends loading too
  }
}

export async function createProduct(product: Omit<Product, 'id'>) {
  const { setLoading, setError, add } = useProducts.getState()

  setLoading(true)
  try {
    const response = await fetch('/api/products', { method: 'POST', body: JSON.stringify(product) })
    add(await response.json()) // ends loading; reports a duplicate id in error
  } catch (error) {
    setError(message(error))
  }
}

Built-in errors(link to this section)

Collection stores refuse writes that would break the list and say why in error. The full list of messages is on the createEntitiesStore page.

errors.ts
const { add, update } = useProducts.getState()

add({ id: 'p1', name: 'Lamp' })
add({ id: 'p1', name: 'Lamp' })
useProducts.getState().error // "Item with id=p1 already exists."

update('missing', { name: 'Nope' })
useProducts.getState().error // "Item with id=missing was not found."

On an entity store, calling update before set reports “Cannot update: no entity is set. Call set() first.” Errors thrown inside your own actions are caught and written to error as well.

What loaded means(link to this section)

loaded answers “has data arrived at least once?”. It turns true with a non-empty initialState, add, addMany, replaceAll or set. Deleting the last item leaves it true: the list was loaded, it's just empty. Only clear() resets it. That makes it the right flag for telling an empty list apart from one that hasn't loaded yet.

Handling state in components(link to this section)

Check the states in this order so a refetch doesn't blank out data that is already on screen:

components/product-list.tsx
'use client'
import { useProducts } from '@/stores/products'

export function ProductList() {
  const { entities, loaded, loading, error, setError } = useProducts()

  if (loading && !loaded) return <p>Loading products…</p>
  if (error) {
    return (
      <p role="alert">
        {error} <button onClick={() => setError(null)}>Dismiss</button>
      </p>
    )
  }
  if (loaded && entities.length === 0) return <p>No products yet.</p>

  return (
    <ul>
      {entities.map((p) => <li key={p.id}>{p.name}</li>)}
    </ul>
  )
}

Found a mistake? Open an issue.