> ## Documentation Index
> Fetch the complete documentation index at: https://docs.stackfront.digital/llms.txt
> Use this file to discover all available pages before exploring further.

# Migrating to 0.2

`0.2.0` ports the missing Shopify commerce surfaces from
`@jaimin28/react-native-shopify` into the SDK while keeping Stackfront's
managed features and react-query architecture. Existing screens keep working:
the legacy members below are deprecated, not removed.

## Package renamed

The package is now **`@stackfront/react-native-shopify`** (it was
`react-native-stackfront-sdk`). Replace the import specifier and the install
line; the `/keychain` subpath moved with it:

```diff theme={null}
- npm install react-native-stackfront-sdk
+ npm install @stackfront/react-native-shopify

- import { StackfrontProvider } from 'react-native-stackfront-sdk';
+ import { StackfrontProvider } from '@stackfront/react-native-shopify';

- import { createKeychainStorage } from 'react-native-stackfront-sdk/keychain';
+ import { createKeychainStorage } from '@stackfront/react-native-shopify/keychain';
```

The native module name (`StackfrontSdk`) and the podspec are unchanged, so no
iOS/Android reconfiguration is needed beyond reinstalling dependencies.

## Auth hardening in 0.2

* **`register(input)`** creates the account and signs in with the same
  credentials in one action. `createAccount(input)` remains for create-only.
* **`createAccount` / `create` now throw** `CustomerCreateError` on Shopify
  `customerUserErrors` instead of returning a silently failed payload.
* **Dead sessions self-heal:** a `customer: null` response clears the token,
  persistence and auth-scoped caches, and `hasSession` flips to `false`.
  `CustomerSessionError` is thrown with `reason: 'invalid' | 'expired'`.
* **Renewal is single-flight**, happens during boot when the token is inside
  the 30-day window, and never overwrites a session that changed mid-request.
* **Double-submit is serialized:** rapid duplicate login/register taps cannot
  create two tokens or two accounts.
* New flags on `useCustomer()`: `isAuthenticated` (alias of `hasSession`),
  `isRestoring`, `isRefreshing`.
* A follow-up profile read failing after a successful login/registration is
  treated as transient — the session stands and the profile query retries.

### Not adopted from the reference package

* **Multi-account sessions / lock-unlock:** the SDK keeps one active session.
  Multiple long-lived Shopify tokens on a device multiply exposure, and a
  lock that only flips a boolean is cosmetic. Use sign-out/sign-in for account
  switching and the platform biometrics for app lock.
* **Optimistic `updateCustomer`:** the SDK keeps server truth; the profile
  cache is seeded with Shopify's response (no rollback flicker).
* **Keychain by default:** keychain remains an explicit opt-in behind the
  `/keychain` subpath so apps that never use it do not bundle the peer.

## At a glance

| Area | Before | Now |
| - | - | - |
| Product detail | `useProduct(handle)` — raw fetch only | options object, variant engine, quantity stepper, `addToCart`, metafields |
| Search | imperative `search()` | debounced `setQuery`, persisted history, suggestions |
| Wishlist | `{ productId, addedAt }` | variant-aware items + one-time storage migration |
| Orders | flat `useOrders()` | paging, detail, tracking, history, prefetch, buckets |
| Addresses | — | `useAddresses` / `useAddress` / `useDefaultAddress` |
| Menus | — | `useMenu` / `useMenus` / `usePrefetchMenu` |
| Checkout | `getCheckoutUrl()` | checkout session lifecycle (`create/open/restore/refresh`) |
| Session storage | AsyncStorage only | optional Keychain adapter behind `./keychain` |

## `useProduct`

The string form still works and `data` is still the raw Storefront node:

```tsx theme={null}
// before — unchanged
const { data, loading, error, refetch } = useProduct(handle);
```

New screens should use the options object and the engine members:

```tsx theme={null}
const {
  product,
  metafields,
  selectedVariant,
  selectedOptions,
  availableOptions,
  disabledOptions,
  price,
  compareAtPrice,
  SKU,
  isAvailable,
  selectOption,
  resetSelections,
  quantity,
  setQuantity,
  incrementQuantity,
  decrementQuantity,
  addToCart,
  isAddingToCart,
} = useProduct({ handle, metafields: [{ namespace: 'custom', key: 'care' }] });
```

* `data` is kept as an alias of `product` (deprecated for new screens).
* `metafields` is a flat array; request them in the same round trip via the
  `metafields` option.
* A selected variant is resolved even before the shopper touches an option
  when the variant matrix has a single valid combination; impossible
  combinations appear in `disabledOptions`.
* `addToCart` uses the SDK's cart and is double-submit guarded.

## `useSearch`

```tsx theme={null}
// before — still works, now deprecated
const { data, loading, error, search } = useSearch();
await search('tee');
```

```tsx theme={null}
// after
const {
  data, results, query, setQuery,
  loading, error, suggestions, history,
  addQueryToHistory, clearHistory, refresh,
} = useSearch({ debounceMs: 300, first: 20 });
```

* `setQuery(text)` updates `query` immediately and performs a debounced
  Storefront read; do not debounce again in the screen.
* History is persisted by the SDK (`search_history`, max 20). If your app kept
  its own recent-search list, migrate it (or switch to the SDK's) to avoid two
  competing histories.
* `suggestions` combines history with titles/vendors/tags from the current
  result page, or pass explicit sources via `availableSuggestionsOptions`.
* `data` is still the raw `search` connection; `results` is the flattened node
  array.

## `useWishlist`

```tsx theme={null}
const {
  items, count,
  isInWishlist,
  toggle, add, remove, clear,
  loading, error, refresh,
} = useWishlist();
```

* Items gained `id`, `variantId`, `selectedOptions`, `title`, `image`,
  `createdAt` and `updatedAt`. `addedAt` remains as a deprecated mirror of
  `createdAt`, so existing cards keep rendering.
* `isInWishlist(productId, variantId?)` is variant-aware; without a variant it
  matches any saved variant of the product.
* `remove(productId, variantId?)` removes one variant, or every variant of the
  product when `variantId` is omitted.
* The first boot after upgrading reads the legacy `wishlist` key, writes
  `wishlist_v2`, and removes the legacy key. No action is required.
* Saving richer items is a drop-in upgrade:

```tsx theme={null}
await toggle({
  productId: product.id,
  variantId: selectedVariant?.id,
  selectedOptions: [{ name: 'Size', value: 'M' }],
  title: product.title,
  image: product.featuredImage,
});
```

## `useOrders`

`useOrders()` without arguments keeps the flat-list contract. Passing any
option switches to the paged form:

```tsx theme={null}
const { orders, pageInfo, refetch } = useOrders({
  first: 20,
  after: pageInfo?.endCursor,
  sortKey: 'PROCESSED_AT', // or 'TOTAL_PRICE'
  reverse: true,
});
```

New hooks: `useInfiniteOrders`, `useOrder`, `useOrderHistory`,
`useOrderTracking`, `usePrefetchOrders`, `usePendingOrders`,
`useCompletedOrders`, `useCancelledOrders`, plus the pure `orders/*` helpers
(`deriveOrderStatus`, `extractTrackingInfo`, `deriveOrderTimeline`,
`toStorefrontOrderSort`, `filterOrders`).

The Storefront API has no standalone order-by-id query and no full order
timeline. `useOrder` is cache-first (falling back to the first page of 50),
and tracking/timeline are derived honestly from `successfulFulfillments`,
`financialStatus`, `fulfillmentStatus` and `canceledAt`. Shopify's official
timeline link is exposed as `statusUrl`.

## Addresses and menus

```tsx theme={null}
const {
  addresses, defaultAddress, loading, error,
  createAddress, updateAddress, deleteAddress, setDefaultAddress, refresh,
} = useAddresses();
```

```tsx theme={null}
const { menu, nodes } = useMenu('main-menu');
const { menus } = useMenus(['main-menu', 'footer']);
```

* Address ids carry a rotating `customer_access_token` suffix. Pass them back
  as received and compare with `sameAddressId(a, b)` — never `===`.
* Menu `route` values are app-agnostic paths (`/products/<handle>`), not a
  hard-coded deep-link scheme.
* Address mutations invalidate both the address book and the customer profile;
  menu reads are public Storefront data.

## `useCheckout`

`getCheckoutUrl()` still works but is deprecated:

```tsx theme={null}
// before
const { getCheckoutUrl } = useCheckout();
const url = await getCheckoutUrl();
```

```tsx theme={null}
// after
const {
  checkout, checkoutUrl, status,
  isCreating, isOpening, isCompleted, isCancelled, isExpired, error,
  create, open, restore, cancel, refresh,
  markCompleted, markCancelled,
} = useCheckout();

const url = await open();          // restores the stored cart if needed
if (url) await Linking.openURL(url);
```

* The session is a view over the cart. Storefront no longer exposes a
  `checkout*` API, `expiresAt`, `completedAt` or a cancel mutation.
* `refresh()` on app foreground discovers a consumed/expired cart (it stops
  resolving). Completion/cancellation deep links are reported by your app via
  `markCompleted()` / `markCancelled()`.
* `cancel()` abandons the session locally and leaves the cart intact.
* The SDK does not open browsers or listen to `Linking`/`AppState`.

## Keychain (optional)

`react-native-keychain` is an optional peer dependency. Keep AsyncStorage
(the default) or opt in:

```tsx theme={null}
import { createKeychainStorage } from '@stackfront/react-native-shopify/keychain';

<StackfrontProvider
  shopDomain={shopDomain}
  apiKey={apiKey}
  auth={{ sessionStorage: createKeychainStorage() }}
>
```

Only the customer session token moves; other SDK caches stay in AsyncStorage.
Token renewal happens automatically near expiry.

## Deprecations

| Deprecated | Replacement |
| - | - |
| `useProduct` string input (`useProduct(handle)`) | `useProduct({ handle })` or `useProduct({ id })` |
| `useProduct().data` | `useProduct().product` |
| `useSearch().search(query)` | `useSearch().setQuery(query)` |
| `useCheckout().getCheckoutUrl()` | `useCheckout().open()` |
| `WishlistItem.addedAt` | `WishlistItem.createdAt` |

Nothing above is removed in 0.2.0.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.