docs: generate medusa-react reference (#6004)

* add new plugin for better organization

* added handling in theme for mutations and query types

* added tsdoc to hooks

* added tsdocs to utility functions

* added tsdoc to providers

* generated reference

* general fixes for generated reference

* generated api reference specs + general fixes

* add missing import react

* split utilities into different directories

* added overview page

* added link to customer authentication section

* fix lint errors

* added changeset

* fix readme

* fixed build error

* added expand fields + other sections to overview

* updated what's new section

* general refactoring

* remove unnecessary query field

* fix links

* added ignoreApi option
This commit is contained in:
Shahed Nasser authored and GitHub committed 2024-01-05 17:03:38 +02:00
1 parent 6fc6a9de6a
commit 7d650771d1
2811 files changed
+231856 -455063

No files matched your search

+143 -2
View File
@@ -1,3 +1,9 @@
/**
* @packageDocumentation
*
* @customNamespace Providers.Cart
*/
import React, { useState } from "react"
import {
useAddShippingMethodToCart,
@@ -10,22 +16,113 @@ import {
import { Cart } from "../types"
interface CartState {
/**
* The currently-used cart.
*/
cart?: Cart
}
interface CartContext extends CartState {
/**
* The cart context available if the {@link CartProvider} is used previously in the React components tree.
*/
export interface CartContext extends CartState {
/**
* A state function used to set the cart object.
*
* @param {Cart} cart - The new value of the cart.
*/
setCart: (cart: Cart) => void
/**
* A mutation used to select a payment processor during checkout.
* Using it is equivalent to using the {@link useSetPaymentSession} mutation.
*/
pay: ReturnType<typeof useSetPaymentSession>
/**
* A mutation used to create a cart.
* Using it is equivalent to using the {@link useCreateCart} mutation.
*/
createCart: ReturnType<typeof useCreateCart>
/**
* A mutation used to initialize payment sessions during checkout.
* Using it is equivalent to using the {@link useCreatePaymentSession} mutation.
*/
startCheckout: ReturnType<typeof useCreatePaymentSession>
/**
* A mutation used to complete the cart and place the order.
* Using it is equivalent to using the {@link useCompleteCart} mutation.
*/
completeCheckout: ReturnType<typeof useCompleteCart>
/**
* A mutation used to update a cart’s details such as region, customer email, shipping address, and more.
* Using it is equivalent to using the {@link useUpdateCart} mutation.
*/
updateCart: ReturnType<typeof useUpdateCart>
/**
* A mutation used to add a shipping method to the cart during checkout.
* Using it is equivalent to using the {@link useAddShippingMethodToCart} mutation.
*/
addShippingMethod: ReturnType<typeof useAddShippingMethodToCart>
/**
* The number of items in the cart.
*/
totalItems: number
}
const CartContext = React.createContext<CartContext | null>(null)
/**
* This hook exposes the context of {@link CartProvider}.
*
* The context provides helper functions and mutations for managing the cart and checkout. You can refer to the following guides for examples on how to use them:
*
* - [How to Add Cart Functionality](https://docs.medusajs.com/modules/carts-and-checkout/storefront/implement-cart)
* - [How to Implement Checkout Flow](https://docs.medusajs.com/modules/carts-and-checkout/storefront/implement-checkout-flow)
*
* @example
* ```tsx title="src/Cart.ts"
* import * as React from "react"
*
* import { useCart } from "medusa-react"
*
* const Cart = () => {
* const handleClick = () => {
* createCart.mutate({}) // create an empty cart
* }
*
* const { cart, createCart } = useCart()
*
* return (
* <div>
* {createCart.isLoading && <div>Loading...</div>}
* {!cart?.id && (
* <button onClick={handleClick}>
* Create cart
* </button>
* )}
* {cart?.id && (
* <div>Cart ID: {cart.id}</div>
* )}
* </div>
* )
* }
*
* export default Cart
* ```
*
* In the example above, you retrieve the `createCart` mutation and `cart` state object using the `useCart` hook.
* If the `cart` is not set, a button is shown. When the button is clicked, the `createCart` mutation is executed, which interacts with the backend and creates a new cart.
*
* After the cart is created, the `cart` state variable is set and its ID is shown instead of the button.
*
* :::note
*
* The example above does not store in the browser the ID of the cart created, so the cart’s data will be gone on refresh.
* You would have to do that using the browser’s [Local Storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage).
*
* :::
*
* @customNamespace Providers.Cart
*/
export const useCart = () => {
const context = React.useContext(CartContext)
if (!context) {
@@ -34,8 +131,14 @@ export const useCart = () => {
return context
}
interface CartProps {
export interface CartProps {
/**
* @ignore
*/
children: React.ReactNode
/**
* An optional initial value to be used for the cart.
*/
initialState?: Cart
}
@@ -44,6 +147,44 @@ const defaultInitialState = {
items: [] as any,
} as Cart
/**
* `CartProvider` makes use of some of the hooks already exposed by `medusa-react` to perform cart operations on the Medusa backend.
* You can use it to create a cart, start the checkout flow, authorize payment sessions, and so on.
*
* It also manages one single global piece of state which represents a cart, exactly like the one created on your Medusa backend.
*
* To use `CartProvider`, you first have to insert it somewhere in your component tree below the {@link Providers.Medusa.MedusaProvider | MedusaProvider}. Then, in any of the child components,
* you can use the {@link useCart} hook exposed by `medusa-react` to get access to cart operations and data.
*
* @param {CartProps} param0 - Props of the provider.
*
* @example
* ```tsx title="src/App.ts"
* import { CartProvider, MedusaProvider } from "medusa-react"
* import Storefront from "./Storefront"
* import { QueryClient } from "@tanstack/react-query"
* import React from "react"
*
* const queryClient = new QueryClient()
*
* function App() {
* return (
* <MedusaProvider
* queryClientProviderProps={{ client: queryClient }}
* baseUrl="http://localhost:9000"
* >
* <CartProvider>
* <Storefront />
* </CartProvider>
* </MedusaProvider>
* )
* }
*
* export default App
* ```
*
* @customNamespace Providers.Cart
*/
export const CartProvider = ({
children,
initialState = defaultInitialState,
@@ -1,3 +1,17 @@
/**
* @packageDocumentation
*
* :::info
*
* This is an experimental feature.
*
* :::
*
* `medusa-react` exposes React Context Providers that facilitate building custom storefronts.
*
* @customNamespace Providers
*/
export * from "./medusa"
export * from "./session-cart"
export * from "./cart"
+103 -7
View File
@@ -1,3 +1,9 @@
/**
* @packageDocumentation
*
* @customNamespace Providers.Medusa
*/
import Medusa from "@medusajs/medusa-js"
import {
QueryClientProvider,
@@ -5,12 +11,50 @@ import {
} from "@tanstack/react-query"
import React from "react"
interface MedusaContextState {
export interface MedusaContextState {
/**
* The Medusa JS Client instance.
*/
client: Medusa
}
const MedusaContext = React.createContext<MedusaContextState | null>(null)
/**
* This hook gives you access to context of {@link MedusaProvider}. It's useful if you want access to the
* [Medusa JS Client](https://docs.medusajs.com/js-client/overview).
*
* @example
* import React from "react"
* import { useMeCustomer, useMedusa } from "medusa-react"
*
* const CustomerLogin = () => {
* const { client } = useMedusa()
* const { refetch: refetchCustomer } = useMeCustomer()
* // ...
*
* const handleLogin = (
* email: string,
* password: string
* ) => {
* client.auth.authenticate({
* email,
* password
* })
* .then(() => {
* // customer is logged-in successfully
* refetchCustomer()
* })
* .catch(() => {
* // an error occurred.
* })
* }
*
* // ...
* }
*
* @customNamespace Providers.Medusa
*/
export const useMedusa = () => {
const context = React.useContext(MedusaContext)
if (!context) {
@@ -19,27 +63,79 @@ export const useMedusa = () => {
return context
}
interface MedusaProviderProps {
export interface MedusaProviderProps {
/**
* The URL to your Medusa backend.
*/
baseUrl: string
/**
* An object used to set the Tanstack Query client. The object requires a `client` property,
* which should be an instance of [QueryClient](https://tanstack.com/query/v4/docs/react/reference/QueryClient).
*/
queryClientProviderProps: QueryClientProviderProps
/**
* @ignore
*/
children: React.ReactNode
/**
* Authentication token
* API key used for authenticating admin requests. Follow [this guide](https://docs.medusajs.com/api/admin#authentication) to learn how to create an API key for an admin user.
*/
apiKey?: string
/**
* PublishableApiKey identifier that defines the scope of resources
* available within the request
* Publishable API key used for storefront requests. You can create a publishable API key either using the
* [admin APIs](https://docs.medusajs.com/development/publishable-api-keys/admin/manage-publishable-api-keys) or the
* [Medusa admin](https://docs.medusajs.com/user-guide/settings/publishable-api-keys#create-publishable-api-key).
*/
publishableApiKey?: string
/**
* Number of times to retry a request if it fails
* @default 3
* Number of times to retry a request if it fails.
*
* @defaultValue 3
*/
maxRetries?: number
/**
* An object of custom headers to pass with every request. Each key of the object is the name of the header, and its value is the header's value.
*
* @defaultValue `{}`
*/
customHeaders?: Record<string, any>
}
/**
* The `MedusaProvider` must be used at the highest possible point in the React component tree. Using any of `medusa-react`'s hooks or providers requires having `MedusaProvider`
* higher in the component tree.
*
* @param {MedusaProviderProps} param0 - Props of the provider.
*
* @example
* ```tsx title="src/App.ts"
* import { MedusaProvider } from "medusa-react"
* import Storefront from "./Storefront"
* import { QueryClient } from "@tanstack/react-query"
* import React from "react"
*
* const queryClient = new QueryClient()
*
* const App = () => {
* return (
* <MedusaProvider
* queryClientProviderProps={{ client: queryClient }}
* baseUrl="http://localhost:9000"
* >
* <Storefront />
* </MedusaProvider>
* )
* }
*
* export default App
* ```
*
* In the example above, you wrap the `Storefront` component with the `MedusaProvider`. `Storefront` is assumed to be the top-level component of your storefront, but you can place `MedusaProvider` at any point in your tree. Only children of `MedusaProvider` can benefit from its hooks.
*
* The `Storefront` component and its child components can now use hooks exposed by Medusa React.
*
* @customNamespace Providers.Medusa
*/
export const MedusaProvider = ({
queryClientProviderProps,
baseUrl,
@@ -1,32 +1,113 @@
/**
* @packageDocumentation
*
* @customNamespace Providers.Session Cart
*/
import React, { useContext, useEffect } from "react"
import { getVariantPrice } from "../helpers"
import { useLocalStorage } from "../hooks/utils"
import { ProductVariant, RegionInfo } from "../types"
import { isArray, isEmpty, isObject } from "../utils"
interface Item {
/**
* A session cart's item.
*/
export interface Item {
/**
* The product variant represented by this item in the cart.
*/
variant: ProductVariant
/**
* The quantity added in the cart.
*/
quantity: number
/**
* The total amount of the item in the cart.
*/
readonly total?: number
}
export interface SessionCartState {
/**
* The region of the cart.
*/
region: RegionInfo
/**
* The items in the cart.
*/
items: Item[]
/**
* The total items in the cart.
*/
totalItems: number
/**
* The total amount of the cart.
*/
total: number
}
interface SessionCartContextState extends SessionCartState {
export interface SessionCartContextState extends SessionCartState {
/**
* A state function used to set the region.
*
* @param region - The new value of the region.
*/
setRegion: (region: RegionInfo) => void
/**
* This function adds an item to the session cart.
*
* @param {Item} item - The item to add.
*/
addItem: (item: Item) => void
/**
* This function removes an item from the session cart.
*
* @param {string} id - The ID of the item.
*/
removeItem: (id: string) => void
/**
* This function updates an item in the session cart.
*
* @param {string} id - The ID of the item.
* @param {Partial<Item>} item - The item's data to update.
*/
updateItem: (id: string, item: Partial<Item>) => void
/**
* A state function used to set the items in the cart.
*
* @param {Item[]} items - The items to set in the cart.
*/
setItems: (items: Item[]) => void
/**
* This function updates an item's quantity in the cart.
*
* @param {string} id - The ID of the item.
* @param {number} quantity - The new quantity of the item.
*/
updateItemQuantity: (id: string, quantity: number) => void
/**
* This function increments the item's quantity in the cart.
*
* @param {string} id - The ID of the item.
*/
incrementItemQuantity: (id: string) => void
/**
* This function decrements the item's quantity in the cart.
*
* @param {string} id - The ID of the item.
*/
decrementItemQuantity: (id: string) => void
/**
* This function retrieves an item's details by its ID.
*
* @param {string} id - The ID of the item.
* @returns {Item | undefined} The item in the cart, if found.
*/
getItem: (id: string) => Item | undefined
/**
* Removes all items in the cart.
*/
clearItems: () => void
}
@@ -111,6 +192,9 @@ const reducer = (state: SessionCartState, action: Action) => {
}
}
/**
* @ignore
*/
export const generateCartState = (state: SessionCartState, items: Item[]) => {
const newItems = generateItems(state.region, items)
return {
@@ -135,8 +219,14 @@ const calculateSessionCartTotal = (items: Item[]) => {
)
}
interface SessionCartProviderProps {
export interface SessionCartProviderProps {
/**
* @ignore
*/
children: React.ReactNode
/**
* An optional initial value to be used for the session cart.
*/
initialState?: SessionCartState
}
@@ -147,6 +237,44 @@ const defaultInitialState: SessionCartState = {
totalItems: 0,
}
/**
* Unlike the {@link Providers.Cart.CartProvider | CartProvider}, `SessionProvider` never interacts with the Medusa backend. It can be used to implement the user experience related to managing a cart’s items.
* Its state variables are JavaScript objects living in the browser, but are in no way communicated with the backend.
*
* You can use the `SessionProvider` as a lightweight client-side cart functionality. It’s not stored in any database or on the Medusa backend.
*
* To use `SessionProvider`, you first have to insert it somewhere in your component tree below the {@link Providers.Medusa.MedusaProvider | MedusaProvider}. Then, in any of the child components,
* you can use the {@link useSessionCart} hook to get access to client-side cart item functionalities.
*
* @param {SessionCartProviderProps} param0 - Props of the provider.
*
* @example
* ```tsx title="src/App.ts"
* import { SessionProvider, MedusaProvider } from "medusa-react"
* import Storefront from "./Storefront"
* import { QueryClient } from "@tanstack/react-query"
* import React from "react"
*
* const queryClient = new QueryClient()
*
* const App = () => {
* return (
* <MedusaProvider
* queryClientProviderProps={{ client: queryClient }}
* baseUrl="http://localhost:9000"
* >
* <SessionProvider>
* <Storefront />
* </SessionProvider>
* </MedusaProvider>
* )
* }
*
* export default App
* ```
*
* @customNamespace Providers.Session Cart
*/
export const SessionCartProvider = ({
initialState = defaultInitialState,
children,
@@ -278,6 +406,28 @@ export const SessionCartProvider = ({
)
}
/**
* This hook exposes the context of {@link SessionCartProvider}.
*
* @example
* The following example assumes that you've added `SessionCartProvider` previously in the React components tree:
*
* ```tsx title="src/Products.ts"
* const Products = () => {
* const { addItem } = useSessionCart()
* // ...
*
* function addToCart(variant: ProductVariant) {
* addItem({
* variant: variant,
* quantity: 1,
* })
* }
* }
* ```
*
* @customNamespace Providers.Session Cart
*/
export const useSessionCart = () => {
const context = useContext(SessionCartContext)
if (!context) {
+281 -15
View File
@@ -1,17 +1,91 @@
/**
* @packageDocumentation
*
* `medusa-react` exposes a set of utility functions that are mainly used to retrieve or format the price of a product variant.
*
* @customNamespace Utilities
*/
import { ProductVariantInfo, RegionInfo } from "../types"
import { isEmpty } from "../utils"
type FormatVariantPriceParams = {
/**
* @interface
*
* Options to format a variant's price.
*/
export type FormatVariantPriceParams = {
/**
* A variant's details.
*/
variant: ProductVariantInfo
/**
* A region's details.
*/
region: RegionInfo
/**
* Whether the computed price should include taxes or not.
*
* @defaultValue true
*/
includeTaxes?: boolean
/**
* The minimum number of fraction digits to use when formatting the price. This is passed as an option to `Intl.NumberFormat` in the underlying layer.
* You can learn more about this method’s options in
* [MDN’s documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#parameters).
*/
minimumFractionDigits?: number
/**
* The maximum number of fraction digits to use when formatting the price. This is passed as an option to `Intl.NumberFormat` which is used within the utility method.
* You can learn more about this method’s options in
* [MDN’s documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#parameters).
*/
maximumFractionDigits?: number
/**
* A BCP 47 language tag. The default value is `en-US`. This is passed as a first parameter to `Intl.NumberFormat` which is used within the utility method.
* You can learn more about this method’s parameters in
* [MDN’s documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#parameters).
*/
locale?: string
}
/**
* Takes a product variant and a region, and converts the variant's price to a localized decimal format
* This utility function can be used to compute the price of a variant for a region and retrieve the formatted amount. For example, `$20.00`.
*
* @param {FormatVariantPriceParams} param0 - Options to format the variant's price.
* @returns {string} The formatted price.
*
* @example
* ```tsx title="src/Products.ts"
* import React from "react"
* import { formatVariantPrice } from "medusa-react"
* import { Product, ProductVariant } from "@medusajs/medusa"
*
* const Products = () => {
* // ...
* return (
* <ul>
* {products?.map((product: Product) => (
* <li key={product.id}>
* {product.title}
* <ul>
* {product.variants.map((variant: ProductVariant) => (
* <li key={variant.id}>
* {formatVariantPrice({
* variant,
* region, // should be retrieved earlier
* })}
* </li>
* ))}
* </ul>
* </li>
* ))}
* </ul>
* )
* }
* ```
*
* @customNamespace Utilities
*/
export const formatVariantPrice = ({
variant,
@@ -28,17 +102,66 @@ export const formatVariantPrice = ({
})
}
type ComputeVariantPriceParams = {
/**
* @interface
*
* Options to format a variant's price.
*/
export type ComputeVariantPriceParams = {
/**
* A variant's details.
*/
variant: ProductVariantInfo
/**
* A region's details.
*/
region: RegionInfo
/**
* Whether the computed price should include taxes or not.
*
* @defaultValue true
*/
includeTaxes?: boolean
}
/**
* Takes a product variant and region, and returns the variant price as a decimal number
* @param params.variant - product variant
* @param params.region - region
* @param params.includeTaxes - whether to include taxes or not
* This utility function can be used to compute the price of a variant for a region and retrieve the amount without formatting.
* For example, `20`. This method is used by {@link formatVariantPrice} before applying the price formatting.
*
* @param {ComputeVariantPriceParams} param0 - Options to compute the variant's price.
* @returns The computed price of the variant.
*
* @example
* ```tsx title="src/Products.ts"
* import React from "react"
* import { computeVariantPrice } from "medusa-react"
* import { Product, ProductVariant } from "@medusajs/medusa"
*
* const Products = () => {
* // ...
* return (
* <ul>
* {products?.map((product: Product) => (
* <li key={product.id}>
* {product.title}
* <ul>
* {product.variants.map((variant: ProductVariant) => (
* <li key={variant.id}>
* {computeVariantPrice({
* variant,
* region, // should be retrieved earlier
* })}
* </li>
* ))}
* </ul>
* </li>
* ))}
* </ul>
* )
* }
* ```
*
* @customNamespace Utilities
*/
export const computeVariantPrice = ({
variant,
@@ -55,10 +178,44 @@ export const computeVariantPrice = ({
}
/**
* Finds the price amount correspoding to the region selected
* @param variant - the product variant
* @param region - the region
* @returns - the price's amount
* This utility function is used to retrieve a variant's price in a region. It doesn't take into account taxes or any options, so you typically wouldn't need this function on its own.
* It's used by the {@link computeVariantPrice} function to retrieve the variant's price in a region before computing the correct price for the options provided.
*
* @param {ProductVariantInfo} variant - The variant's details.
* @param {RegionInfo} region - The region's details.
* @returns {number} The variant's price in a region.
*
* @example
* ```tsx title="src/Products.ts"
* import React from "react"
* import { getVariantPrice } from "medusa-react"
* import { Product, ProductVariant } from "@medusajs/medusa"
*
* const Products = () => {
* // ...
* return (
* <ul>
* {products?.map((product: Product) => (
* <li key={product.id}>
* {product.title}
* <ul>
* {product.variants.map((variant: ProductVariant) => (
* <li key={variant.id}>
* {getVariantPrice(
* variant,
* region, // should be retrieved earlier
* )}
* </li>
* ))}
* </ul>
* </li>
* ))}
* </ul>
* )
* }
* ```
*
* @customNamespace Utilities
*/
export const getVariantPrice = (
variant: ProductVariantInfo,
@@ -72,14 +229,54 @@ export const getVariantPrice = (
return price?.amount || 0
}
type ComputeAmountParams = {
/**
* Options to compute an amount.
*/
export type ComputeAmountParams = {
/**
* The original amount used for computation.
*/
amount: number
/**
* The region's details.
*/
region: RegionInfo
/**
* Whether the computed price should include taxes or not.
*
* @defaultValue true
*/
includeTaxes?: boolean
}
/**
* Takes an amount, a region, and returns the amount as a decimal including or excluding taxes
* This utility function can be used to compute the price of an amount for a region and retrieve the amount without formatting. For example, `20`.
* This function is used by {@link formatAmount} before applying the price formatting.
*
* The main difference between this utility function and {@link computeVariantPrice} is that you don’t need to pass a complete variant object. This can be used with any number.
*
* @param {ComputeAmountParams} params0 - The options to compute the amount.
* @returns {number} The computed amount.
*
* @example
* ```tsx title="src/MyComponent.ts"
* import React from "react"
* import { computeAmount } from "medusa-react"
*
* const MyComponent = () => {
* // ...
* return (
* <div>
* {computeAmount({
* amount,
* region, // should be retrieved earlier
* })}
* </div>
* )
* }
* ```
*
* @customNamespace Utilities
*/
export const computeAmount = ({
amount,
@@ -95,17 +292,81 @@ export const computeAmount = ({
return amountWithTaxes
}
type FormatAmountParams = {
/**
* Options to format an amount.
*/
export type FormatAmountParams = {
/**
* The original amount used for computation.
*/
amount: number
/**
* The region's details.
*/
region: RegionInfo
/**
* Whether the computed price should include taxes or not.
*
* @defaultValue true
*/
includeTaxes?: boolean
/**
* The minimum number of fraction digits to use when formatting the price. This is passed as an option to `Intl.NumberFormat` in the underlying layer.
* You can learn more about this method’s options in
* [MDN’s documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#parameters).
*/
minimumFractionDigits?: number
/**
* The maximum number of fraction digits to use when formatting the price. This is passed as an option to `Intl.NumberFormat` which is used within the utility method.
* You can learn more about this method’s options in
* [MDN’s documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#parameters).
*/
maximumFractionDigits?: number
/**
* A BCP 47 language tag. The default value is `en-US`. This is passed as a first parameter to `Intl.NumberFormat` which is used within the utility method.
* You can learn more about this method’s parameters in
* [MDN’s documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#parameters).
*/
locale?: string
}
/**
* Takes an amount and a region, and converts the amount to a localized decimal format
* This utility function can be used to compute the price of an amount for a region and retrieve the formatted amount. For example, `$20.00`.
*
* The main difference between this utility function and {@link formatVariantPrice} is that you don’t need to pass a complete variant object. This can be used with any number.
*
* @param {FormatAmountParams} param0 - Options to format the amount.
* @returns {string} The formatted price.
*
* @example
* import React from "react"
* import { formatVariantPrice } from "medusa-react"
* import { Product, ProductVariant } from "@medusajs/medusa"
*
* const Products = () => {
* // ...
* return (
* <ul>
* {products?.map((product: Product) => (
* <li key={product.id}>
* {product.title}
* <ul>
* {product.variants.map((variant: ProductVariant) => (
* <li key={variant.id}>
* {formatVariantPrice({
* variant,
* region, // should be retrieved earlier
* })}
* </li>
* ))}
* </ul>
* </li>
* ))}
* </ul>
* )
* }
*
* @customNamespace Utilities
*/
export const formatAmount = ({
amount,
@@ -166,3 +427,8 @@ type ConvertToLocaleParams = {
maximumFractionDigits?: number
locale?: string
}
/**
* @internal We need to export these types so that they're included in the generated reference documentation.
*/
export { ProductVariantInfo, RegionInfo }
@@ -1,2 +1,17 @@
/**
* @packageDocumentation
*
* Queries and mutations listed here are used to send requests to the [Admin Auth API Routes](https://docs.medusajs.com/api/admin#auth_getauth).
*
* They allow admin users to manage their session, such as login or log out.
* You can send authenticated requests for an admin user either using the Cookie header, their API token, or the JWT Token.
* When you log the admin user in using the {@link Hooks.Admin.Auth.useAdminLogin | user authentication} hook, Medusa React will automatically attach the
* cookie header in all subsequent requests.
*
* Related Guide: [How to implement user profiles](https://docs.medusajs.com/modules/users/admin/manage-profile).
*
* @customNamespace Hooks.Admin.Auth
*/
export * from "./queries"
export * from "./mutations"
export * from "./mutations"
@@ -9,7 +9,41 @@ import { useMedusa } from "../../../contexts/medusa"
import { buildOptions } from "../../utils/buildOptions"
import { adminAuthKeys } from "./queries"
/**
* This hook is used to log a User in using their credentials. If the user is authenticated successfully,
* the cookie is automatically attached to subsequent requests sent with other hooks.
*
* @example
* import React from "react"
* import { useAdminLogin } from "medusa-react"
*
* const Login = () => {
* const adminLogin = useAdminLogin()
* // ...
*
* const handleLogin = () => {
* adminLogin.mutate({
* email: "user@example.com",
* password: "supersecret",
* }, {
* onSuccess: ({ user }) => {
* console.log(user)
* }
* })
* }
*
* // ...
* }
*
* export default Login
*
* @customNamespace Hooks.Admin.Auth
* @category Mutations
*/
export const useAdminLogin = (
/**
* stuff again
*/
options?: UseMutationOptions<Response<AdminAuthRes>, Error, AdminPostAuthReq>
) => {
const { client } = useMedusa()
@@ -21,6 +55,36 @@ export const useAdminLogin = (
)
}
/**
* This hook is used to Log out the user and remove their authentication session. This will only work if you're using Cookie session for authentication. If the API token is still passed in the header,
* the user is still authorized to perform admin functionalities in other API Routes.
*
* This hook requires {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* @example
* import React from "react"
* import { useAdminDeleteSession } from "medusa-react"
*
* const Logout = () => {
* const adminLogout = useAdminDeleteSession()
* // ...
*
* const handleLogout = () => {
* adminLogout.mutate(undefined, {
* onSuccess: () => {
* // user logged out.
* }
* })
* }
*
* // ...
* }
*
* export default Logout
*
* @customNamespace Hooks.Admin.Auth
* @category Mutations
*/
export const useAdminDeleteSession = (
options?: UseMutationOptions<Response<void>, Error, void>
) => {
@@ -11,6 +11,31 @@ export const adminAuthKeys = queryKeysFactory(ADMIN_AUTH_QUERY_KEY)
type AuthQueryKey = typeof adminAuthKeys
/**
* This hook is used to get the currently logged in user's details. Can also be used to check if there is an authenticated user.
*
* This hook requires {@link Hooks~Admin~Auth~useAdminLogin | user authentication}.
*
* @example
* import React from "react"
* import { useAdminGetSession } from "medusa-react"
*
* const Profile = () => {
* const { user, isLoading } = useAdminGetSession()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {user && <span>{user.email}</span>}
* </div>
* )
* }
*
* export default Profile
*
* @customNamespace Hooks.Admin.Auth
* @category Queries
*/
export const useAdminGetSession = (
options?: UseQueryOptionsWrapper<
Response<AdminAuthRes>,
@@ -1,2 +1,17 @@
/**
* @packageDocumentation
*
* Queries and mutations listed here are used to send requests to the [Admin Batch Job API Routes](https://docs.medusajs.com/api/admin#batch-jobs).
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* A batch job is a task that is performed by the Medusa backend asynchronusly. For example, the Import Product feature is implemented using batch jobs.
* The methods in this class allow admins to manage the batch jobs and their state.
*
* Related Guide: [How to import products](https://docs.medusajs.com/modules/products/admin/import-products).
*
* @customNamespace Hooks.Admin.Batch Jobs
*/
export * from "./queries"
export * from "./mutations"
@@ -11,9 +11,36 @@ import { buildOptions } from "../../utils/buildOptions"
import { adminBatchJobsKeys } from "./queries"
/**
* Hook returns functions for creating batch jobs.
*
* @param options
* This hook creates a Batch Job to be executed asynchronously in the Medusa backend. If `dry_run` is set to `true`, the batch job will not be executed until the it is confirmed,
* which can be done using the {@link useAdminConfirmBatchJob} hook.
*
* @example
* import React from "react"
* import { useAdminCreateBatchJob } from "medusa-react"
*
* const CreateBatchJob = () => {
* const createBatchJob = useAdminCreateBatchJob()
* // ...
*
* const handleCreateBatchJob = () => {
* createBatchJob.mutate({
* type: "publish-products",
* context: {},
* dry_run: true
* }, {
* onSuccess: ({ batch_job }) => {
* console.log(batch_job)
* }
* })
* }
*
* // ...
* }
*
* export default CreateBatchJob
*
* @customNamespace Hooks.Admin.Batch Jobs
* @category Mutations
*/
export const useAdminCreateBatchJob = (
options?: UseMutationOptions<
@@ -32,12 +59,40 @@ export const useAdminCreateBatchJob = (
}
/**
* Hook return functions for canceling a batch job
*
* @param id - id of the batch job
* @param options
* This hook marks a batch job as canceled. When a batch job is canceled, the processing of the batch job doesn’t automatically stop.
*
* @example
* import React from "react"
* import { useAdminCancelBatchJob } from "medusa-react"
*
* type Props = {
* batchJobId: string
* }
*
* const BatchJob = ({ batchJobId }: Props) => {
* const cancelBatchJob = useAdminCancelBatchJob(batchJobId)
* // ...
*
* const handleCancel = () => {
* cancelBatchJob.mutate(undefined, {
* onSuccess: ({ batch_job }) => {
* console.log(batch_job)
* }
* })
* }
*
* // ...
* }
*
* export default BatchJob
*
* @customNamespace Hooks.Admin.Batch Jobs
* @category Mutations
*/
export const useAdminCancelBatchJob = (
/**
* The ID of the batch job.
*/
id: string,
options?: UseMutationOptions<Response<AdminBatchJobRes>, Error>
) => {
@@ -55,12 +110,39 @@ export const useAdminCancelBatchJob = (
}
/**
* Hook return functions for confirming a batch job
*
* @param id - id of the batch job
* @param options
* @reactMutationHook
*
* When a batch job is created, it's not executed automatically if `dry_run` is set to `true`. This hook confirms that the batch job should be executed.
*
* @example
* import React from "react"
* import { useAdminConfirmBatchJob } from "medusa-react"
*
* type Props = {
* batchJobId: string
* }
*
* const BatchJob = ({ batchJobId }: Props) => {
* const confirmBatchJob = useAdminConfirmBatchJob(batchJobId)
* // ...
*
* const handleConfirm = () => {
* confirmBatchJob.mutate(undefined, {
* onSuccess: ({ batch_job }) => {
* console.log(batch_job)
* }
* })
* }
*
* // ...
* }
*
* export default BatchJob
*/
export const useAdminConfirmBatchJob = (
/**
* The ID of the batch job.
*/
id: string,
options?: UseMutationOptions<Response<AdminBatchJobRes>, Error>
) => {
@@ -15,7 +15,127 @@ export const adminBatchJobsKeys = queryKeysFactory(ADMIN_COLLECTIONS_QUERY_KEY)
type BatchJobsQueryKey = typeof adminBatchJobsKeys
/**
* This hook retrieves a list of Batch Jobs. The batch jobs can be filtered by fields such as `type` or `confirmed_at`. The batch jobs can also be sorted or paginated.
*
* @example
* To list batch jobs:
*
* ```ts
* import React from "react"
* import { useAdminBatchJobs } from "medusa-react"
*
* const BatchJobs = () => {
* const {
* batch_jobs,
* limit,
* offset,
* count,
* isLoading
* } = useAdminBatchJobs()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {batch_jobs?.length && (
* <ul>
* {batch_jobs.map((batchJob) => (
* <li key={batchJob.id}>
* {batchJob.id}
* </li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default BatchJobs
* ```
*
* To specify relations that should be retrieved within the batch jobs:
*
* ```ts
* import React from "react"
* import { useAdminBatchJobs } from "medusa-react"
*
* const BatchJobs = () => {
* const {
* batch_jobs,
* limit,
* offset,
* count,
* isLoading
* } = useAdminBatchJobs({
* expand: "created_by_user",
* limit: 10,
* offset: 0
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {batch_jobs?.length && (
* <ul>
* {batch_jobs.map((batchJob) => (
* <li key={batchJob.id}>
* {batchJob.id}
* </li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default BatchJobs
* ```
*
* By default, only the first `10` records are retrieved. You can control pagination by specifying the `limit` and `offset` properties:
*
* ```ts
* import React from "react"
* import { useAdminBatchJobs } from "medusa-react"
*
* const BatchJobs = () => {
* const {
* batch_jobs,
* limit,
* offset,
* count,
* isLoading
* } = useAdminBatchJobs({
* expand: "created_by_user",
* limit: 20,
* offset: 0
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {batch_jobs?.length && (
* <ul>
* {batch_jobs.map((batchJob) => (
* <li key={batchJob.id}>
* {batchJob.id}
* </li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default BatchJobs
* ```
*
* @customNamespace Hooks.Admin.Batch Jobs
* @category Queries
*/
export const useAdminBatchJobs = (
/**
* Filters and pagination configurations to apply on the retrieved batch jobs.
*/
query?: AdminGetBatchParams,
options?: UseQueryOptionsWrapper<
Response<AdminBatchJobListRes>,
@@ -32,7 +152,37 @@ export const useAdminBatchJobs = (
return { ...data, ...rest } as const
}
/**
* This hook retrieves the details of a batch job.
*
* @example
* import React from "react"
* import { useAdminBatchJob } from "medusa-react"
*
* type Props = {
* batchJobId: string
* }
*
* const BatchJob = ({ batchJobId }: Props) => {
* const { batch_job, isLoading } = useAdminBatchJob(batchJobId)
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {batch_job && <span>{batch_job.created_by}</span>}
* </div>
* )
* }
*
* export default BatchJob
*
* @customNamespace Hooks.Admin.Batch Jobs
* @category Queries
*/
export const useAdminBatchJob = (
/**
* The ID of the batch job.
*/
id: string,
options?: UseQueryOptionsWrapper<
Response<AdminBatchJobRes>,
@@ -1 +1,16 @@
/**
* @packageDocumentation
*
* Mutations listed here are used to send requests to the [Admin Order API Routes related to claims](https://docs.medusajs.com/api/admin#orders).
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* A claim represents a return or replacement request of order items. It allows refunding the customer or replacing some or all of its
* order items with new items.
*
* Related Guide: [How to manage claims](https://docs.medusajs.com/modules/orders/admin/manage-claims).
*
* @customNamespace Hooks.Admin.Claims
*/
export * from "./mutations"
@@ -17,7 +17,50 @@ import { adminProductKeys } from "../products"
import { adminVariantKeys } from "../variants"
import { adminOrderKeys } from "./../orders/queries"
/**
* This hook creates a claim for an order. If a return shipping method is specified, a return will also be created and associated with the claim. If the claim's type is `refund`,
* the refund is processed as well.
*
* @example
* import React from "react"
* import { useAdminCreateClaim } from "medusa-react"
*
* type Props = {
* orderId: string
* }
*
* const CreateClaim = ({ orderId }: Props) => {
* const createClaim = useAdminCreateClaim(orderId)
* // ...
*
* const handleCreate = (itemId: string) => {
* createClaim.mutate({
* type: "refund",
* claim_items: [
* {
* item_id: itemId,
* quantity: 1,
* },
* ],
* }, {
* onSuccess: ({ order }) => {
* console.log(order.claims)
* }
* })
* }
*
* // ...
* }
*
* export default CreateClaim
*
* @customNamespace Hooks.Admin.Claims
* @category Mutations
*/
export const useAdminCreateClaim = (
/**
* The ID of the order the claim is associated with.
*/
orderId: string,
options?: UseMutationOptions<
Response<AdminOrdersRes>,
@@ -35,12 +78,57 @@ export const useAdminCreateClaim = (
)
}
export type AdminUpdateClaimReq = AdminPostOrdersOrderClaimsClaimReq & {
/**
* The claim's ID.
*/
claim_id: string
}
/**
* This hook updates a claim's details.
*
* @example
* import React from "react"
* import { useAdminUpdateClaim } from "medusa-react"
*
* type Props = {
* orderId: string
* claimId: string
* }
*
* const Claim = ({ orderId, claimId }: Props) => {
* const updateClaim = useAdminUpdateClaim(orderId)
* // ...
*
* const handleUpdate = () => {
* updateClaim.mutate({
* claim_id: claimId,
* no_notification: false
* }, {
* onSuccess: ({ order }) => {
* console.log(order.claims)
* }
* })
* }
*
* // ...
* }
*
* export default Claim
*
* @customNamespace Hooks.Admin.Claims
* @category Mutations
*/
export const useAdminUpdateClaim = (
/**
* The ID of the order the claim is associated with.
*/
orderId: string,
options?: UseMutationOptions<
Response<AdminOrdersRes>,
Error,
AdminPostOrdersOrderClaimsClaimReq & { claim_id: string }
AdminUpdateClaimReq
>
) => {
const { client } = useMedusa()
@@ -50,15 +138,53 @@ export const useAdminUpdateClaim = (
({
claim_id,
...payload
}: AdminPostOrdersOrderClaimsClaimReq & { claim_id: string }) =>
}: AdminUpdateClaimReq) =>
client.admin.orders.updateClaim(orderId, claim_id, payload),
buildOptions(queryClient, adminOrderKeys.detail(orderId), options)
)
}
/**
* This hook cancels a claim and change its status. A claim can't be canceled if it has a refund, if its fulfillments haven't been canceled,
* of if its associated return hasn't been canceled.
*
* @typeParamDefinition string - The claim's ID.
*
* @example
* import React from "react"
* import { useAdminCancelClaim } from "medusa-react"
*
* type Props = {
* orderId: string
* claimId: string
* }
*
* const Claim = ({ orderId, claimId }: Props) => {
* const cancelClaim = useAdminCancelClaim(orderId)
* // ...
*
* const handleCancel = () => {
* cancelClaim.mutate(claimId)
* }
*
* // ...
* }
*
* export default Claim
*
* @customNamespace Hooks.Admin.Claims
* @category Mutations
*/
export const useAdminCancelClaim = (
/**
* The ID of the order the claim is associated with.
*/
orderId: string,
options?: UseMutationOptions<Response<AdminOrdersRes>, Error, string>
options?: UseMutationOptions<
Response<AdminOrdersRes>,
Error,
string
>
) => {
const { client } = useMedusa()
const queryClient = useQueryClient()
@@ -69,12 +195,55 @@ export const useAdminCancelClaim = (
)
}
/**
* This hook creates a Fulfillment for a Claim, and change its fulfillment status to `partially_fulfilled` or `fulfilled` depending on whether all the items were fulfilled.
* It may also change the status to `requires_action` if any actions are required.
*
* @example
* import React from "react"
* import { useAdminFulfillClaim } from "medusa-react"
*
* type Props = {
* orderId: string
* claimId: string
* }
*
* const Claim = ({ orderId, claimId }: Props) => {
* const fulfillClaim = useAdminFulfillClaim(orderId)
* // ...
*
* const handleFulfill = () => {
* fulfillClaim.mutate({
* claim_id: claimId,
* }, {
* onSuccess: ({ order }) => {
* console.log(order.claims)
* }
* })
* }
*
* // ...
* }
*
* export default Claim
*
* @customNamespace Hooks.Admin.Claims
* @category Mutations
*/
export const useAdminFulfillClaim = (
/**
* The ID of the order the claim is associated with.
*/
orderId: string,
options?: UseMutationOptions<
Response<AdminOrdersRes>,
Error,
AdminPostOrdersOrderClaimsClaimFulfillmentsReq & { claim_id: string }
AdminPostOrdersOrderClaimsClaimFulfillmentsReq & {
/**
* The claim's ID.
*/
claim_id: string
}
>
) => {
const { client } = useMedusa()
@@ -98,12 +267,66 @@ export const useAdminFulfillClaim = (
)
}
/**
* The cancelation details.
*/
export type AdminCancelClaimFulfillmentReq = {
/**
* The claim's ID.
*/
claim_id: string;
/**
* The fulfillment's ID.
*/
fulfillment_id: string
}
/**
* This hook cancels a claim's fulfillment and change its fulfillment status to `canceled`.
*
* @example
* import React from "react"
* import { useAdminCancelClaimFulfillment } from "medusa-react"
*
* type Props = {
* orderId: string
* claimId: string
* }
*
* const Claim = ({ orderId, claimId }: Props) => {
* const cancelFulfillment = useAdminCancelClaimFulfillment(
* orderId
* )
* // ...
*
* const handleCancel = (fulfillmentId: string) => {
* cancelFulfillment.mutate({
* claim_id: claimId,
* fulfillment_id: fulfillmentId,
* }, {
* onSuccess: ({ order }) => {
* console.log(order.claims)
* }
* })
* }
*
* // ...
* }
*
* export default Claim
*
* @customNamespace Hooks.Admin.Claims
* @category Mutations
*/
export const useAdminCancelClaimFulfillment = (
/**
* The ID of the order the claim is associated with.
*/
orderId: string,
options?: UseMutationOptions<
Response<AdminOrdersRes>,
Error,
{ claim_id: string; fulfillment_id: string }
AdminCancelClaimFulfillmentReq
>
) => {
const { client } = useMedusa()
@@ -113,10 +336,7 @@ export const useAdminCancelClaimFulfillment = (
({
claim_id,
fulfillment_id,
}: {
claim_id: string
fulfillment_id: string
}) =>
}: AdminCancelClaimFulfillmentReq) =>
client.admin.orders.cancelClaimFulfillment(
orderId,
claim_id,
@@ -126,12 +346,56 @@ export const useAdminCancelClaimFulfillment = (
)
}
/**
* This hook creates a shipment for the claim and mark its fulfillment as shipped. If the shipment is created successfully, this changes the claim's fulfillment status
* to either `partially_shipped` or `shipped`, depending on whether all the items were shipped.
*
* @example
* import React from "react"
* import { useAdminCreateClaimShipment } from "medusa-react"
*
* type Props = {
* orderId: string
* claimId: string
* }
*
* const Claim = ({ orderId, claimId }: Props) => {
* const createShipment = useAdminCreateClaimShipment(orderId)
* // ...
*
* const handleCreateShipment = (fulfillmentId: string) => {
* createShipment.mutate({
* claim_id: claimId,
* fulfillment_id: fulfillmentId,
* }, {
* onSuccess: ({ order }) => {
* console.log(order.claims)
* }
* })
* }
*
* // ...
* }
*
* export default Claim
*
* @customNamespace Hooks.Admin.Claims
* @category Mutations
*/
export const useAdminCreateClaimShipment = (
/**
* The ID of the order the claim is associated with.
*/
orderId: string,
options?: UseMutationOptions<
Response<AdminOrdersRes>,
Error,
AdminPostOrdersOrderClaimsClaimShipmentsReq & { claim_id: string }
AdminPostOrdersOrderClaimsClaimShipmentsReq & {
/**
* The claim's ID.
*/
claim_id: string
}
>
) => {
const { client } = useMedusa()
@@ -1,2 +1,14 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Product Collection API Routes](https://docs.medusajs.com/api/admin#product-collections).
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* A product collection is used to organize products for different purposes such as marketing or discount purposes. For example, you can create a Summer Collection.
*
* @customNamespace Hooks.Admin.Product Collections
*/
export * from "./queries"
export * from "./mutations"
@@ -17,6 +17,35 @@ import { useMedusa } from "../../../contexts/medusa"
import { buildOptions } from "../../utils/buildOptions"
import { adminCollectionKeys } from "./queries"
/**
* This hook creates a product collection.
*
* @example
* import React from "react"
* import { useAdminCreateCollection } from "medusa-react"
*
* const CreateCollection = () => {
* const createCollection = useAdminCreateCollection()
* // ...
*
* const handleCreate = (title: string) => {
* createCollection.mutate({
* title
* }, {
* onSuccess: ({ collection }) => {
* console.log(collection.id)
* }
* })
* }
*
* // ...
* }
*
* export default CreateCollection
*
* @customNamespace Hooks.Admin.Product Collections
* @category Mutations
*/
export const useAdminCreateCollection = (
options?: UseMutationOptions<
Response<AdminCollectionsRes>,
@@ -33,7 +62,43 @@ export const useAdminCreateCollection = (
)
}
/**
* This hook updates a product collection's details.
*
* @example
* import React from "react"
* import { useAdminUpdateCollection } from "medusa-react"
*
* type Props = {
* collectionId: string
* }
*
* const Collection = ({ collectionId }: Props) => {
* const updateCollection = useAdminUpdateCollection(collectionId)
* // ...
*
* const handleUpdate = (title: string) => {
* updateCollection.mutate({
* title
* }, {
* onSuccess: ({ collection }) => {
* console.log(collection.id)
* }
* })
* }
*
* // ...
* }
*
* export default Collection
*
* @customNamespace Hooks.Admin.Product Collections
* @category Mutations
*/
export const useAdminUpdateCollection = (
/**
* The product collection's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminCollectionsRes>,
@@ -54,7 +119,41 @@ export const useAdminUpdateCollection = (
)
}
/**
* This hook deletes a product collection. This does not delete associated products.
*
* @example
* import React from "react"
* import { useAdminDeleteCollection } from "medusa-react"
*
* type Props = {
* collectionId: string
* }
*
* const Collection = ({ collectionId }: Props) => {
* const deleteCollection = useAdminDeleteCollection(collectionId)
* // ...
*
* const handleDelete = (title: string) => {
* deleteCollection.mutate(void 0, {
* onSuccess: ({ id, object, deleted }) => {
* console.log(id)
* }
* })
* }
*
* // ...
* }
*
* export default Collection
*
* @customNamespace Hooks.Admin.Product Collections
* @category Mutations
*/
export const useAdminDeleteCollection = (
/**
* The product collection's ID.
*/
id: string,
options?: UseMutationOptions<Response<AdminCollectionsDeleteRes>, Error, void>
) => {
@@ -71,12 +170,42 @@ export const useAdminDeleteCollection = (
}
/**
* Hook returns function for adding multiple products to a collection.
*
* @param id - id of the collection in which products are being added
* @param options
* This hook adds products to a collection.
*
* @example
* import React from "react"
* import { useAdminAddProductsToCollection } from "medusa-react"
*
* type Props = {
* collectionId: string
* }
*
* const Collection = ({ collectionId }: Props) => {
* const addProducts = useAdminAddProductsToCollection(collectionId)
* // ...
*
* const handleAddProducts = (productIds: string[]) => {
* addProducts.mutate({
* product_ids: productIds
* }, {
* onSuccess: ({ collection }) => {
* console.log(collection.products)
* }
* })
* }
*
* // ...
* }
*
* export default Collection
*
* @customNamespace Hooks.Admin.Product Collections
* @category Mutations
*/
export const useAdminAddProductsToCollection = (
/**
* The product collection's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminCollectionsRes>,
@@ -99,12 +228,43 @@ export const useAdminAddProductsToCollection = (
}
/**
* Hook returns function for removal of multiple products from a collection.
*
* @param id - id of the collection from which products will be removed
* @param options
* This hook removes a list of products from a collection. This would not delete the product,
* only the association between the product and the collection.
*
* @example
* import React from "react"
* import { useAdminRemoveProductsFromCollection } from "medusa-react"
*
* type Props = {
* collectionId: string
* }
*
* const Collection = ({ collectionId }: Props) => {
* const removeProducts = useAdminRemoveProductsFromCollection(collectionId)
* // ...
*
* const handleRemoveProducts = (productIds: string[]) => {
* removeProducts.mutate({
* product_ids: productIds
* }, {
* onSuccess: ({ id, object, removed_products }) => {
* console.log(removed_products)
* }
* })
* }
*
* // ...
* }
*
* export default Collection
*
* @customNamespace Hooks.Admin.Product Collections
* @category Mutations
*/
export const useAdminRemoveProductsFromCollection = (
/**
* The product collection's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminDeleteProductsFromCollectionRes>,
@@ -15,7 +15,79 @@ export const adminCollectionKeys = queryKeysFactory(ADMIN_COLLECTIONS_QUERY_KEY)
type CollectionsQueryKey = typeof adminCollectionKeys
/**
* This hook retrieves a list of product collections. The product collections can be filtered by fields such as `handle` or `title`.
* The collections can also be sorted or paginated.
*
* @example
* To list product collections:
*
* ```tsx
* import React from "react"
* import { useAdminCollections } from "medusa-react"
*
* const Collections = () => {
* const { collections, isLoading } = useAdminCollections()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {collections && !collections.length && <span>
* No Product Collections
* </span>}
* {collections && collections.length > 0 && (
* <ul>
* {collections.map((collection) => (
* <li key={collection.id}>{collection.title}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default Collections
* ```
*
* By default, only the first `10` records are retrieved. You can control pagination by specifying the `limit` and `offset` properties:
*
* ```tsx
* import React from "react"
* import { useAdminCollections } from "medusa-react"
*
* const Collections = () => {
* const { collections, limit, offset, isLoading } = useAdminCollections({
* limit: 15,
* offset: 0
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {collections && !collections.length && <span>
* No Product Collections
* </span>}
* {collections && collections.length > 0 && (
* <ul>
* {collections.map((collection) => (
* <li key={collection.id}>{collection.title}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default Collections
* ```
*
* @customNamespace Hooks.Admin.Product Collections
* @category Queries
*/
export const useAdminCollections = (
/**
* Filters and pagination configurations to apply on the retrieved product collections.
*/
query?: AdminGetCollectionsParams,
options?: UseQueryOptionsWrapper<
Response<AdminCollectionsListRes>,
@@ -32,7 +104,37 @@ export const useAdminCollections = (
return { ...data, ...rest } as const
}
/**
* This hook retrieves a product collection by its ID. The products associated with it are expanded and returned as well.
*
* @example
* import React from "react"
* import { useAdminCollection } from "medusa-react"
*
* type Props = {
* collectionId: string
* }
*
* const Collection = ({ collectionId }: Props) => {
* const { collection, isLoading } = useAdminCollection(collectionId)
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {collection && <span>{collection.title}</span>}
* </div>
* )
* }
*
* export default Collection
*
* @customNamespace Hooks.Admin.Product Collections
* @category Queries
*/
export const useAdminCollection = (
/**
* The product collection's ID.
*/
id: string,
options?: UseQueryOptionsWrapper<
Response<AdminCollectionsRes>,
@@ -1,2 +1,17 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Currency API Routes](https://docs.medusajs.com/api/admin#currencies).
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* A store can use unlimited currencies, and each region must be associated with at least one currency.
* Currencies are defined within the Medusa backend. The methods in this class allow admins to list and update currencies.
*
* Related Guide: [How to manage currencies](https://docs.medusajs.com/modules/regions-and-currencies/admin/manage-currencies).
*
* @customNamespace Hooks.Admin.Currencies
*/
export * from "./mutations"
export * from "./queries"
@@ -12,7 +12,43 @@ import { useMedusa } from "../../../contexts/medusa"
import { buildOptions } from "../../utils/buildOptions"
import { adminCurrenciesKeys } from "./queries"
/**
* This hook updates a currency's details.
*
* @example
* import React from "react"
* import { useAdminUpdateCurrency } from "medusa-react"
*
* type Props = {
* currencyCode: string
* }
*
* const Currency = ({ currencyCode }: Props) => {
* const updateCurrency = useAdminUpdateCurrency(currencyCode)
* // ...
*
* const handleUpdate = (includes_tax: boolean) => {
* updateCurrency.mutate({
* includes_tax,
* }, {
* onSuccess: ({ currency }) => {
* console.log(currency)
* }
* })
* }
*
* // ...
* }
*
* export default Currency
*
* @customNamespace Hooks.Admin.Currencies
* @category Mutations
*/
export const useAdminUpdateCurrency = (
/**
* The currency's code.
*/
code: string,
options?: UseMutationOptions<
Response<AdminCurrenciesRes>,
@@ -14,7 +14,79 @@ export const adminCurrenciesKeys = queryKeysFactory(ADMIN_CURRENCIES_QUERY_KEY)
type CurrenciesQueryKey = typeof adminCurrenciesKeys
/**
* This hook retrieves a list of currencies. The currencies can be filtered by fields such as `code`.
* The currencies can also be sorted or paginated.
*
* @example
* To list currencies:
*
* ```ts
* import React from "react"
* import { useAdminCurrencies } from "medusa-react"
*
* const Currencies = () => {
* const { currencies, isLoading } = useAdminCurrencies()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {currencies && !currencies.length && (
* <span>No Currencies</span>
* )}
* {currencies && currencies.length > 0 && (
* <ul>
* {currencies.map((currency) => (
* <li key={currency.code}>{currency.name}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default Currencies
* ```
*
* By default, only the first `20` records are retrieved. You can control pagination by specifying the `limit` and `offset` properties:
*
* ```ts
* import React from "react"
* import { useAdminCurrencies } from "medusa-react"
*
* const Currencies = () => {
* const { currencies, limit, offset, isLoading } = useAdminCurrencies({
* limit: 10,
* offset: 0
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {currencies && !currencies.length && (
* <span>No Currencies</span>
* )}
* {currencies && currencies.length > 0 && (
* <ul>
* {currencies.map((currency) => (
* <li key={currency.code}>{currency.name}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default Currencies
* ```
*
* @customNamespace Hooks.Admin.Currencies
* @category Queries
*/
export const useAdminCurrencies = (
/**
* Filters and pagination configurations to apply on retrieved currencies.
*/
query?: AdminGetCurrenciesParams,
options?: UseQueryOptionsWrapper<
Response<AdminCurrenciesListRes>,
@@ -1,2 +1,11 @@
/**
* @packageDocumentation
*
* This class is used to send requests custom API Routes. All its method
* are available in the JS Client under the `medusa.admin.custom` property.
*
* @customNamespace Hooks.Admin.Custom
*/
export { useAdminCustomDelete, useAdminCustomPost } from "./mutations"
export { useAdminCustomQuery } from "./queries"
@@ -91,12 +91,69 @@ export const buildCustomOptions = <
}
}
/**
* This hook sends a `POST` request to a custom API Route.
*
* @typeParam TPayload - The type of accepted body parameters which defaults to `Record<string, any>`.
* @typeParam TResponse - The type of response, which defaults to `any`.
* @typeParamDefinition TResponse - The response based on the specified type for `TResponse`.
* @typeParamDefinition TPayload - The payload based on the specified type for `TPayload`.
*
* @example
* import React from "react"
* import { useAdminCustomPost } from "medusa-react"
* import Post from "./models/Post"
*
* type PostRequest = {
* title: string
* }
* type PostResponse = {
* post: Post
* }
*
* const Custom = () => {
* const customPost = useAdminCustomPost
* <PostRequest, PostResponse>(
* "/blog/posts",
* ["posts"]
* )
*
* // ...
*
* const handleAction = (title: string) => {
* customPost.mutate({
* title
* }, {
* onSuccess: ({ post }) => {
* console.log(post)
* }
* })
* }
*
* // ...
* }
*
* export default Custom
*
* @customNamespace Hooks.Admin.Custom
* @category Mutations
*/
export const useAdminCustomPost = <
TPayload extends Record<string, any>,
TResponse
>(
/**
* The path to the custom endpoint.
*/
path: string,
/**
* A list of query keys, used to invalidate data.
*/
queryKey: QueryKey,
/**
* A list of related domains that should be invalidated and refetch when the mutation
* function is invoked.
*/
relatedDomains?: RelatedDomains,
options?: UseMutationOptions<Response<TResponse>, Error, TPayload>
) => {
@@ -110,9 +167,57 @@ export const useAdminCustomPost = <
)
}
/**
* This hook sends a `DELETE` request to a custom API Route.
*
* @typeParam TResponse - The response's type which defaults to `any`.
* @typeParamDefinition TResponse - The response based on the type provided for `TResponse`.
*
* @example
* import React from "react"
* import { useAdminCustomDelete } from "medusa-react"
*
* type Props = {
* customId: string
* }
*
* const Custom = ({ customId }: Props) => {
* const customDelete = useAdminCustomDelete(
* `/blog/posts/${customId}`,
* ["posts"]
* )
*
* // ...
*
* const handleAction = (title: string) => {
* customDelete.mutate(void 0, {
* onSuccess: () => {
* // Delete action successful
* }
* })
* }
*
* // ...
* }
*
* export default Custom
*
* @customNamespace Hooks.Admin.Custom
* @category Mutations
*/
export const useAdminCustomDelete = <TResponse>(
/**
* The path to the custom endpoint.
*/
path: string,
/**
* A list of query keys, used to invalidate data.
*/
queryKey: QueryKey,
/**
* A list of related domains that should be invalidated and refetch when the mutation
* function is invoked.
*/
relatedDomains?: RelatedDomains,
options?: UseMutationOptions<Response<TResponse>, Error, void>
) => {
@@ -3,12 +3,74 @@ import { QueryKey, useQuery } from "@tanstack/react-query"
import { useMedusa } from "../../../contexts"
import { UseQueryOptionsWrapper } from "../../../types"
/**
* This hook sends a `GET` request to a custom API Route.
*
* @typeParam TQuery - The type of accepted query parameters which defaults to `Record<string, any>`.
* @typeParam TResponse - The type of response which defaults to `any`.
* @typeParamDefinition TQuery - The query parameters based on the type specified for `TQuery`.
* @typeParamDefinition TResponse - The response based on the type specified for `TResponse`.
*
* @example
* import React from "react"
* import { useAdminCustomQuery } from "medusa-react"
* import Post from "./models/Post"
*
* type RequestQuery = {
* title: string
* }
*
* type ResponseData = {
* posts: Post
* }
*
* const Custom = () => {
* const { data, isLoading } = useAdminCustomQuery
* <RequestQuery, ResponseData>(
* "/blog/posts",
* ["posts"],
* {
* title: "My post"
* }
* )
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {data?.posts && !data.posts.length && (
* <span>No Post</span>
* )}
* {data?.posts && data.posts?.length > 0 && (
* <ul>
* {data.posts.map((post) => (
* <li key={post.id}>{post.title}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default Custom
*
* @customNamespace Hooks.Admin.Custom
* @category Mutations
*/
export const useAdminCustomQuery = <
TQuery extends Record<string, any>,
TResponse = any
>(
/**
* The path to the custom endpoint.
*/
path: string,
/**
* A list of query keys, used to invalidate data.
*/
queryKey: QueryKey,
/**
* Query parameters to pass to the request.
*/
query?: TQuery,
options?: UseQueryOptionsWrapper<
Response<TResponse>,
@@ -1,2 +1,17 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Customer Group API Routes](https://docs.medusajs.com/api/admin#customer-groups).
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* Customer Groups can be used to organize customers that share similar data or attributes into dedicated groups.
* This can be useful for different purposes such as setting a different price for a specific customer group.
*
* Related Guide: [How to manage customer groups](https://docs.medusajs.com/modules/customers/admin/manage-customer-groups).
*
* @customNamespace Hooks.Admin.Customer Groups
*/
export * from "./queries"
export * from "./mutations"
@@ -18,9 +18,29 @@ import { buildOptions } from "../../utils/buildOptions"
import { adminCustomerGroupKeys } from "./queries"
/**
* Hook returns functions for creating customer groups.
*
* @param options
* This hook creates a customer group.
*
* @example
* import React from "react"
* import { useAdminCreateCustomerGroup } from "medusa-react"
*
* const CreateCustomerGroup = () => {
* const createCustomerGroup = useAdminCreateCustomerGroup()
* // ...
*
* const handleCreate = (name: string) => {
* createCustomerGroup.mutate({
* name,
* })
* }
*
* // ...
* }
*
* export default CreateCustomerGroup
*
* @customNamespace Hooks.Admin.Customer Groups
* @category Mutations
*/
export const useAdminCreateCustomerGroup = (
options?: UseMutationOptions<
@@ -40,12 +60,40 @@ export const useAdminCreateCustomerGroup = (
}
/**
* Hook return functions for updating a customer group.
*
* @param id - id of the customer group that is being updated
* @param options
* This hook updates a customer group's details.
*
* @example
* import React from "react"
* import { useAdminUpdateCustomerGroup } from "medusa-react"
*
* type Props = {
* customerGroupId: string
* }
*
* const CustomerGroup = ({ customerGroupId }: Props) => {
* const updateCustomerGroup = useAdminUpdateCustomerGroup(
* customerGroupId
* )
* // ..
*
* const handleUpdate = (name: string) => {
* updateCustomerGroup.mutate({
* name,
* })
* }
*
* // ...
* }
*
* export default CustomerGroup
*
* @customNamespace Hooks.Admin.Customer Groups
* @category Mutations
*/
export const useAdminUpdateCustomerGroup = (
/**
* The customer group's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminCustomerGroupsRes>,
@@ -68,12 +116,38 @@ export const useAdminUpdateCustomerGroup = (
}
/**
* Hook return functions for deleting a customer group.
* This hook deletes a customer group. This doesn't delete the customers associated with the customer group.
*
* @param id - id of the customer group that is being deleted
* @param options
* @example
* import React from "react"
* import { useAdminDeleteCustomerGroup } from "medusa-react"
*
* type Props = {
* customerGroupId: string
* }
*
* const CustomerGroup = ({ customerGroupId }: Props) => {
* const deleteCustomerGroup = useAdminDeleteCustomerGroup(
* customerGroupId
* )
* // ...
*
* const handleDeleteCustomerGroup = () => {
* deleteCustomerGroup.mutate()
* }
*
* // ...
* }
*
* export default CustomerGroup
*
* @customNamespace Hooks.Admin.Customer Groups
* @category Mutations
*/
export const useAdminDeleteCustomerGroup = (
/**
* The customer group's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminCustomerGroupsDeleteRes>,
@@ -95,12 +169,46 @@ export const useAdminDeleteCustomerGroup = (
}
/**
* Hook returns functions for addition of multiple customers to a customer group.
* The hook adds a list of customers to a customer group.
*
* @param id - id of the customer group in which customers are being added
* @param options
* @example
* import React from "react"
* import {
* useAdminAddCustomersToCustomerGroup,
* } from "medusa-react"
*
* type Props = {
* customerGroupId: string
* }
*
* const CustomerGroup = ({ customerGroupId }: Props) => {
* const addCustomers = useAdminAddCustomersToCustomerGroup(
* customerGroupId
* )
* // ...
*
* const handleAddCustomers= (customerId: string) => {
* addCustomers.mutate({
* customer_ids: [
* {
* id: customerId,
* },
* ],
* })
* }
*
* // ...
* }
*
* export default CustomerGroup
*
* @customNamespace Hooks.Admin.Customer Groups
* @category Mutations
*/
export const useAdminAddCustomersToCustomerGroup = (
/**
* The customer group's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminCustomerGroupsRes>,
@@ -126,12 +234,48 @@ export const useAdminAddCustomersToCustomerGroup = (
}
/**
* Hook returns function for removal of multiple customers from a customer group.
*
* @param id - id of a group from which customers will be removed
* @param options
* This hook removes a list of customers from a customer group. This doesn't delete the customer,
* only the association between the customer and the customer group.
*
* @example
* import React from "react"
* import {
* useAdminRemoveCustomersFromCustomerGroup,
* } from "medusa-react"
*
* type Props = {
* customerGroupId: string
* }
*
* const CustomerGroup = ({ customerGroupId }: Props) => {
* const removeCustomers =
* useAdminRemoveCustomersFromCustomerGroup(
* customerGroupId
* )
* // ...
*
* const handleRemoveCustomer = (customerId: string) => {
* removeCustomers.mutate({
* customer_ids: [
* {
* id: customerId,
* },
* ],
* })
* }
*
* // ...
* }
*
* export default CustomerGroup
*
* @customNamespace Hooks.Admin.Customer Groups
* @category Mutations
*/
export const useAdminRemoveCustomersFromCustomerGroup = (
/**
* The customer group's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminCustomerGroupsRes>,
@@ -15,6 +15,9 @@ import { queryKeysFactory } from "../../utils"
const ADMIN_CUSTOMER_GROUPS_QUERY_KEY = `admin_customer_groups` as const
/**
* @ignore
*/
export const adminCustomerGroupKeys = {
...queryKeysFactory(ADMIN_CUSTOMER_GROUPS_QUERY_KEY),
detailCustomer(id: string, query?: AdminGetCustomersParams) {
@@ -25,14 +28,43 @@ export const adminCustomerGroupKeys = {
type CustomerGroupQueryKeys = typeof adminCustomerGroupKeys
/**
* Hook retrieves a customer group by id.
*
* @param id - customer group id
* @param query - query params
* @param options
* This hook retrieves a customer group by its ID. You can expand the customer group's relations or
* select the fields that should be returned.
*
* @example
* import React from "react"
* import { useAdminCustomerGroup } from "medusa-react"
*
* type Props = {
* customerGroupId: string
* }
*
* const CustomerGroup = ({ customerGroupId }: Props) => {
* const { customer_group, isLoading } = useAdminCustomerGroup(
* customerGroupId
* )
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {customer_group && <span>{customer_group.name}</span>}
* </div>
* )
* }
*
* export default CustomerGroup
*
* @customNamespace Hooks.Admin.Customer Groups
* @category Queries
*/
export const useAdminCustomerGroup = (
/**
* The customer group's ID.
*/
id: string,
/**
* Configurations to apply on the retrieved customer group.
*/
query?: AdminGetCustomerGroupsGroupParams,
options?: UseQueryOptionsWrapper<
Response<AdminCustomerGroupsRes>,
@@ -50,12 +82,133 @@ export const useAdminCustomerGroup = (
}
/**
* Hook retrieves a list of customer groups.
*
* @param query - pagination/filtering params
* @param options
* This hook retrieves a list of customer groups. The customer groups can be filtered by fields such as `name` or `id`.
* The customer groups can also be sorted or paginated.
*
* @example
* To list customer groups:
*
* ```tsx
* import React from "react"
* import { useAdminCustomerGroups } from "medusa-react"
*
* const CustomerGroups = () => {
* const {
* customer_groups,
* isLoading,
* } = useAdminCustomerGroups()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {customer_groups && !customer_groups.length && (
* <span>No Customer Groups</span>
* )}
* {customer_groups && customer_groups.length > 0 && (
* <ul>
* {customer_groups.map(
* (customerGroup) => (
* <li key={customerGroup.id}>
* {customerGroup.name}
* </li>
* )
* )}
* </ul>
* )}
* </div>
* )
* }
*
* export default CustomerGroups
* ```
*
* To specify relations that should be retrieved within the customer groups:
*
* ```tsx
* import React from "react"
* import { useAdminCustomerGroups } from "medusa-react"
*
* const CustomerGroups = () => {
* const {
* customer_groups,
* isLoading,
* } = useAdminCustomerGroups({
* expand: "customers"
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {customer_groups && !customer_groups.length && (
* <span>No Customer Groups</span>
* )}
* {customer_groups && customer_groups.length > 0 && (
* <ul>
* {customer_groups.map(
* (customerGroup) => (
* <li key={customerGroup.id}>
* {customerGroup.name}
* </li>
* )
* )}
* </ul>
* )}
* </div>
* )
* }
*
* export default CustomerGroups
* ```
*
* By default, only the first `10` records are retrieved. You can control pagination by specifying the `limit` and `offset` properties:
*
* ```tsx
* import React from "react"
* import { useAdminCustomerGroups } from "medusa-react"
*
* const CustomerGroups = () => {
* const {
* customer_groups,
* limit,
* offset,
* isLoading,
* } = useAdminCustomerGroups({
* expand: "customers",
* limit: 15,
* offset: 0
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {customer_groups && !customer_groups.length && (
* <span>No Customer Groups</span>
* )}
* {customer_groups && customer_groups.length > 0 && (
* <ul>
* {customer_groups.map(
* (customerGroup) => (
* <li key={customerGroup.id}>
* {customerGroup.name}
* </li>
* )
* )}
* </ul>
* )}
* </div>
* )
* }
*
* export default CustomerGroups
* ```
*
* @customNamespace Hooks.Admin.Customer Groups
* @category Queries
*/
export const useAdminCustomerGroups = (
/**
* Filters and pagination configurations to apply on the retrieved customer groups.
*/
query?: AdminGetCustomerGroupsParams,
options?: UseQueryOptionsWrapper<
Response<AdminCustomerGroupsListRes>,
@@ -73,14 +226,55 @@ export const useAdminCustomerGroups = (
}
/**
* Hook retrieves a list of customers that belong to provided groups.
*
* @param id - customer group id
* @param query - pagination/filtering params
* @param options
* This hook retrieves a list of customers in a customer group. The customers can be filtered
* by the `query` field. The customers can also be paginated.
*
* @example
* import React from "react"
* import { useAdminCustomerGroupCustomers } from "medusa-react"
*
* type Props = {
* customerGroupId: string
* }
*
* const CustomerGroup = ({ customerGroupId }: Props) => {
* const {
* customers,
* isLoading,
* } = useAdminCustomerGroupCustomers(
* customerGroupId
* )
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {customers && !customers.length && (
* <span>No customers</span>
* )}
* {customers && customers.length > 0 && (
* <ul>
* {customers.map((customer) => (
* <li key={customer.id}>{customer.first_name}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default CustomerGroup
*
* @customNamespace Hooks.Admin.Customer Groups
* @category Queries
*/
export const useAdminCustomerGroupCustomers = (
/**
* The customer group's ID.
*/
id: string,
/**
* Filters and pagination configurations to apply on the retrieved customers.
*/
query?: AdminGetCustomersParams,
options?: UseQueryOptionsWrapper<
Response<AdminCustomersListRes>,
@@ -1,2 +1,14 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Customer API Routes](https://docs.medusajs.com/api/admin#customers).
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* Related Guide: [How to manage customers](https://docs.medusajs.com/modules/customers/admin/manage-customers).
*
* @customNamespace Hooks.Admin.Customers
*/
export * from "./queries"
export * from "./mutations"
@@ -15,6 +15,40 @@ import { useMedusa } from "../../../contexts"
import { buildOptions } from "../../utils/buildOptions"
import { adminCustomerKeys } from "./queries"
/**
* This hook creates a customer as an admin.
*
* @example
* import React from "react"
* import { useAdminCreateCustomer } from "medusa-react"
*
* type CustomerData = {
* first_name: string
* last_name: string
* email: string
* password: string
* }
*
* const CreateCustomer = () => {
* const createCustomer = useAdminCreateCustomer()
* // ...
*
* const handleCreate = (customerData: CustomerData) => {
* createCustomer.mutate(customerData, {
* onSuccess: ({ customer }) => {
* console.log(customer.id)
* }
* })
* }
*
* // ...
* }
*
* export default CreateCustomer
*
* @customNamespace Hooks.Admin.Customers
* @category Mutations
*/
export const useAdminCreateCustomer = (
options?: UseMutationOptions<
Response<AdminCustomersRes>,
@@ -31,7 +65,44 @@ export const useAdminCreateCustomer = (
)
}
/**
* This hook updates a customer's details.
*
* @example
* import React from "react"
* import { useAdminUpdateCustomer } from "medusa-react"
*
* type CustomerData = {
* first_name: string
* last_name: string
* email: string
* password: string
* }
*
* type Props = {
* customerId: string
* }
*
* const Customer = ({ customerId }: Props) => {
* const updateCustomer = useAdminUpdateCustomer(customerId)
* // ...
*
* const handleUpdate = (customerData: CustomerData) => {
* updateCustomer.mutate(customerData)
* }
*
* // ...
* }
*
* export default Customer
*
* @customNamespace Hooks.Admin.Customers
* @category Mutations
*/
export const useAdminUpdateCustomer = (
/**
* The customer's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminCustomersRes>,
@@ -15,7 +15,86 @@ export const adminCustomerKeys = queryKeysFactory(ADMIN_CUSTOMERS_QUERY_KEY)
type CustomerQueryKeys = typeof adminCustomerKeys
/**
* This hook retrieves a list of Customers. The customers can be filtered by fields such as
* `q` or `groups`. The customers can also be paginated.
*
* @example
* To list customers:
*
* ```tsx
* import React from "react"
* import { useAdminCustomers } from "medusa-react"
*
* const Customers = () => {
* const { customers, isLoading } = useAdminCustomers()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {customers && !customers.length && (
* <span>No customers</span>
* )}
* {customers && customers.length > 0 && (
* <ul>
* {customers.map((customer) => (
* <li key={customer.id}>{customer.first_name}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default Customers
* ```
*
* You can specify relations to be retrieved within each customer. In addition, by default, only the first `50` records are retrieved.
* You can control pagination by specifying the `limit` and `offset` properties:
*
* ```tsx
* import React from "react"
* import { useAdminCustomers } from "medusa-react"
*
* const Customers = () => {
* const {
* customers,
* limit,
* offset,
* isLoading
* } = useAdminCustomers({
* expand: "billing_address",
* limit: 20,
* offset: 0
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {customers && !customers.length && (
* <span>No customers</span>
* )}
* {customers && customers.length > 0 && (
* <ul>
* {customers.map((customer) => (
* <li key={customer.id}>{customer.first_name}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default Customers
* ```
*
* @customNamespace Hooks.Admin.Customers
* @category Queries
*/
export const useAdminCustomers = (
/**
* Filters and pagination configurations to apply on the retrieved customers.
*/
query?: AdminGetCustomersParams,
options?: UseQueryOptionsWrapper<
Response<AdminCustomersListRes>,
@@ -32,7 +111,39 @@ export const useAdminCustomers = (
return { ...data, ...rest } as const
}
/**
* This hook retrieves the details of a customer.
*
* @example
* import React from "react"
* import { useAdminCustomer } from "medusa-react"
*
* type Props = {
* customerId: string
* }
*
* const Customer = ({ customerId }: Props) => {
* const { customer, isLoading } = useAdminCustomer(
* customerId
* )
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {customer && <span>{customer.first_name}</span>}
* </div>
* )
* }
*
* export default Customer
*
* @customNamespace Hooks.Admin.Customers
* @category Queries
*/
export const useAdminCustomer = (
/**
* The customer's ID.
*/
id: string,
options?: UseQueryOptionsWrapper<
Response<AdminCustomersRes>,
@@ -1,2 +1,17 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Discount API Routes](https://docs.medusajs.com/api/admin#discounts).
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* Admins can create discounts with conditions and rules, providing them with advanced settings for variety of cases.
* The methods in this class can be used to manage discounts, their conditions, resources, and more.
*
* Related Guide: [How to manage discounts](https://docs.medusajs.com/modules/discounts/admin/manage-discounts).
*
* @customNamespace Hooks.Admin.Discounts
*/
export * from "./queries"
export * from "./mutations"
@@ -20,9 +20,115 @@ import { useMedusa } from "../../../contexts"
import { buildOptions } from "../../utils/buildOptions"
import { adminDiscountKeys } from "./queries"
/**
* This hook adds a batch of resources to a discount condition. The type of resource depends on the type of discount condition.
* For example, if the discount condition's type is `products`, the resources being added should be products.
*
* @example
* To add resources to a discount condition:
*
* ```tsx
* import React from "react"
* import {
* useAdminAddDiscountConditionResourceBatch
* } from "medusa-react"
*
* type Props = {
* discountId: string
* conditionId: string
* }
*
* const DiscountCondition = ({
* discountId,
* conditionId
* }: Props) => {
* const addConditionResources = useAdminAddDiscountConditionResourceBatch(
* discountId,
* conditionId
* )
* // ...
*
* const handleAdd = (itemId: string) => {
* addConditionResources.mutate({
* resources: [
* {
* id: itemId
* }
* ]
* }, {
* onSuccess: ({ discount }) => {
* console.log(discount.id)
* }
* })
* }
*
* // ...
* }
*
* export default DiscountCondition
* ```
*
* To specify relations to include in the returned discount:
*
* ```tsx
* import React from "react"
* import {
* useAdminAddDiscountConditionResourceBatch
* } from "medusa-react"
*
* type Props = {
* discountId: string
* conditionId: string
* }
*
* const DiscountCondition = ({
* discountId,
* conditionId
* }: Props) => {
* const addConditionResources = useAdminAddDiscountConditionResourceBatch(
* discountId,
* conditionId,
* {
* expand: "rule"
* }
* )
* // ...
*
* const handleAdd = (itemId: string) => {
* addConditionResources.mutate({
* resources: [
* {
* id: itemId
* }
* ]
* }, {
* onSuccess: ({ discount }) => {
* console.log(discount.id)
* }
* })
* }
*
* // ...
* }
*
* export default DiscountCondition
* ```
*
* @customNamespace Hooks.Admin.Discounts
* @category Mutations
*/
export const useAdminAddDiscountConditionResourceBatch = (
/**
* The ID of the discount the condition belongs to.
*/
discountId: string,
/**
* The discount condition's ID.
*/
conditionId: string,
/**
* Configurations to apply on the retrieved discount.
*/
query?: AdminPostDiscountsDiscountConditionsConditionBatchParams,
options?: UseMutationOptions<
Response<AdminDiscountsRes>,
@@ -44,8 +150,61 @@ export const useAdminAddDiscountConditionResourceBatch = (
)
}
/**
* This hook remove a batch of resources from a discount condition. This will only remove the association between the resource and
* the discount condition, not the resource itself.
*
* @example
* import React from "react"
* import {
* useAdminDeleteDiscountConditionResourceBatch
* } from "medusa-react"
*
* type Props = {
* discountId: string
* conditionId: string
* }
*
* const DiscountCondition = ({
* discountId,
* conditionId
* }: Props) => {
* const deleteConditionResource = useAdminDeleteDiscountConditionResourceBatch(
* discountId,
* conditionId,
* )
* // ...
*
* const handleDelete = (itemId: string) => {
* deleteConditionResource.mutate({
* resources: [
* {
* id: itemId
* }
* ]
* }, {
* onSuccess: ({ discount }) => {
* console.log(discount.id)
* }
* })
* }
*
* // ...
* }
*
* export default DiscountCondition
*
* @customNamespace Hooks.Admin.Discounts
* @category Mutations
*/
export const useAdminDeleteDiscountConditionResourceBatch = (
/**
* The ID of the discount the condition belongs to.
*/
discountId: string,
/**
* The discount condition's ID.
*/
conditionId: string,
options?: UseMutationOptions<
Response<AdminDiscountsRes>,
@@ -67,6 +226,51 @@ export const useAdminDeleteDiscountConditionResourceBatch = (
)
}
/**
* This hook creates a discount with a given set of rules that defines how the discount is applied.
*
* @example
* import React from "react"
* import {
* useAdminCreateDiscount,
* } from "medusa-react"
* import {
* AllocationType,
* DiscountRuleType,
* } from "@medusajs/medusa"
*
* const CreateDiscount = () => {
* const createDiscount = useAdminCreateDiscount()
* // ...
*
* const handleCreate = (
* currencyCode: string,
* regionId: string
* ) => {
* // ...
* createDiscount.mutate({
* code: currencyCode,
* rule: {
* type: DiscountRuleType.FIXED,
* value: 10,
* allocation: AllocationType.ITEM,
* },
* regions: [
* regionId,
* ],
* is_dynamic: false,
* is_disabled: false,
* })
* }
*
* // ...
* }
*
* export default CreateDiscount
*
* @customNamespace Hooks.Admin.Discounts
* @category Mutations
*/
export const useAdminCreateDiscount = (
options?: UseMutationOptions<
Response<AdminDiscountsRes>,
@@ -82,7 +286,39 @@ export const useAdminCreateDiscount = (
)
}
/**
* This hook updates a discount with a given set of rules that define how the discount is applied.
*
* @example
* import React from "react"
* import { useAdminUpdateDiscount } from "medusa-react"
*
* type Props = {
* discountId: string
* }
*
* const Discount = ({ discountId }: Props) => {
* const updateDiscount = useAdminUpdateDiscount(discountId)
* // ...
*
* const handleUpdate = (isDisabled: boolean) => {
* updateDiscount.mutate({
* is_disabled: isDisabled,
* })
* }
*
* // ...
* }
*
* export default Discount
*
* @customNamespace Hooks.Admin.Discounts
* @category Mutations
*/
export const useAdminUpdateDiscount = (
/**
* The discount's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminDiscountsRes>,
@@ -99,7 +335,33 @@ export const useAdminUpdateDiscount = (
)
}
/**
* This hook deletes a discount. Deleting the discount will make it unavailable for customers to use.
*
* @example
* import React from "react"
* import { useAdminDeleteDiscount } from "medusa-react"
*
* const Discount = () => {
* const deleteDiscount = useAdminDeleteDiscount(discount_id)
* // ...
*
* const handleDelete = () => {
* deleteDiscount.mutate()
* }
*
* // ...
* }
*
* export default Discount
*
* @customNamespace Hooks.Admin.Discounts
* @category Mutations
*/
export const useAdminDeleteDiscount = (
/**
* The discount's ID.
*/
id: string,
options?: UseMutationOptions<Response<AdminDiscountsDeleteRes>, Error, void>
) => {
@@ -111,7 +373,43 @@ export const useAdminDeleteDiscount = (
)
}
/**
* This hook adds a Region to the list of Regions a Discount can be used in.
*
* @typeParamDefinition string - The ID of the region to add.
*
* @example
* import React from "react"
* import { useAdminDiscountAddRegion } from "medusa-react"
*
* type Props = {
* discountId: string
* }
*
* const Discount = ({ discountId }: Props) => {
* const addRegion = useAdminDiscountAddRegion(discountId)
* // ...
*
* const handleAdd = (regionId: string) => {
* addRegion.mutate(regionId, {
* onSuccess: ({ discount }) => {
* console.log(discount.regions)
* }
* })
* }
*
* // ...
* }
*
* export default Discount
*
* @customNamespace Hooks.Admin.Discounts
* @category Mutations
*/
export const useAdminDiscountAddRegion = (
/**
* The discount's ID.
*/
id: string,
options?: UseMutationOptions<Response<AdminDiscountsRes>, Error, string>
) => {
@@ -123,7 +421,44 @@ export const useAdminDiscountAddRegion = (
)
}
/**
* This hook removes a Region from the list of Regions that a Discount can be used in.
* This does not delete a region, only the association between it and the discount.
*
* @typeParamDefinition string - The ID of the region to remove.
*
* @example
* import React from "react"
* import { useAdminDiscountRemoveRegion } from "medusa-react"
*
* type Props = {
* discountId: string
* }
*
* const Discount = ({ discountId }: Props) => {
* const deleteRegion = useAdminDiscountRemoveRegion(discountId)
* // ...
*
* const handleDelete = (regionId: string) => {
* deleteRegion.mutate(regionId, {
* onSuccess: ({ discount }) => {
* console.log(discount.regions)
* }
* })
* }
*
* // ...
* }
*
* export default Discount
*
* @customNamespace Hooks.Admin.Discounts
* @category Mutations
*/
export const useAdminDiscountRemoveRegion = (
/**
* The discount's ID.
*/
id: string,
options?: UseMutationOptions<Response<AdminDiscountsRes>, Error, string>
) => {
@@ -135,7 +470,48 @@ export const useAdminDiscountRemoveRegion = (
)
}
/**
* This hook creates a dynamic unique code that can map to a parent discount. This is useful if you want to
* automatically generate codes with the same rules and conditions.
*
* @example
* import React from "react"
* import { useAdminCreateDynamicDiscountCode } from "medusa-react"
*
* type Props = {
* discountId: string
* }
*
* const Discount = ({ discountId }: Props) => {
* const createDynamicDiscount = useAdminCreateDynamicDiscountCode(discountId)
* // ...
*
* const handleCreate = (
* code: string,
* usageLimit: number
* ) => {
* createDynamicDiscount.mutate({
* code,
* usage_limit: usageLimit
* }, {
* onSuccess: ({ discount }) => {
* console.log(discount.is_dynamic)
* }
* })
* }
*
* // ...
* }
*
* export default Discount
*
* @customNamespace Hooks.Admin.Discounts
* @category Mutations
*/
export const useAdminCreateDynamicDiscountCode = (
/**
* The discount's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminDiscountsRes>,
@@ -156,7 +532,43 @@ export const useAdminCreateDynamicDiscountCode = (
)
}
/**
* This hook deletes a dynamic code from a discount.
*
* @typeParamDefinition string - The code of the dynamic discount to delete.
*
* @example
* import React from "react"
* import { useAdminDeleteDynamicDiscountCode } from "medusa-react"
*
* type Props = {
* discountId: string
* }
*
* const Discount = ({ discountId }: Props) => {
* const deleteDynamicDiscount = useAdminDeleteDynamicDiscountCode(discountId)
* // ...
*
* const handleDelete = (code: string) => {
* deleteDynamicDiscount.mutate(code, {
* onSuccess: ({ discount }) => {
* console.log(discount.is_dynamic)
* }
* })
* }
*
* // ...
* }
*
* export default Discount
*
* @customNamespace Hooks.Admin.Discounts
* @category Mutations
*/
export const useAdminDeleteDynamicDiscountCode = (
/**
* The discount's ID.
*/
id: string,
options?: UseMutationOptions<Response<AdminDiscountsRes>, Error, string>
) => {
@@ -172,7 +584,50 @@ export const useAdminDeleteDynamicDiscountCode = (
)
}
/**
* This hook creates a discount condition. Only one of `products`, `product_types`, `product_collections`, `product_tags`, and `customer_groups`
* should be provided in the `payload` parameter, based on the type of discount condition. For example, if the discount condition's type is `products`,
* the `products` field should be provided in the `payload` parameter.
*
* @example
* import React from "react"
* import { DiscountConditionOperator } from "@medusajs/medusa"
* import { useAdminDiscountCreateCondition } from "medusa-react"
*
* type Props = {
* discountId: string
* }
*
* const Discount = ({ discountId }: Props) => {
* const createCondition = useAdminDiscountCreateCondition(discountId)
* // ...
*
* const handleCreateCondition = (
* operator: DiscountConditionOperator,
* products: string[]
* ) => {
* createCondition.mutate({
* operator,
* products
* }, {
* onSuccess: ({ discount }) => {
* console.log(discount.id)
* }
* })
* }
*
* // ...
* }
*
* export default Discount
*
* @customNamespace Hooks.Admin.Discounts
* @category Mutations
*/
export const useAdminDiscountCreateCondition = (
/**
* The discount's ID.
*/
discountId: string,
options?: UseMutationOptions<
Response<AdminDiscountsRes>,
@@ -189,8 +644,58 @@ export const useAdminDiscountCreateCondition = (
)
}
/**
* Update a discount condition. Only one of `products`, `product_types`, `product_collections`, `product_tags`, and `customer_groups`
* should be provided in the `payload` parameter, based on the type of discount condition. For example, if the discount condition's
* type is `products`, the `products` field should be provided in the `payload` parameter.
*
* @example
* import React from "react"
* import { useAdminDiscountUpdateCondition } from "medusa-react"
*
* type Props = {
* discountId: string
* conditionId: string
* }
*
* const DiscountCondition = ({
* discountId,
* conditionId
* }: Props) => {
* const update = useAdminDiscountUpdateCondition(
* discountId,
* conditionId
* )
* // ...
*
* const handleUpdate = (
* products: string[]
* ) => {
* update.mutate({
* products
* }, {
* onSuccess: ({ discount }) => {
* console.log(discount.id)
* }
* })
* }
*
* // ...
* }
*
* export default DiscountCondition
*
* @customNamespace Hooks.Admin.Discounts
* @category Mutations
*/
export const useAdminDiscountUpdateCondition = (
/**
* The discount's ID.
*/
discountId: string,
/**
* The discount condition's ID.
*/
conditionId: string,
options?: UseMutationOptions<
Response<AdminDiscountsRes>,
@@ -207,7 +712,47 @@ export const useAdminDiscountUpdateCondition = (
)
}
/**
* This hook deletes a discount condition. This doesn't delete resources associated to the discount condition.
*
* @typeParamDefinition string - The ID of the condition to delete.
*
* @example
* import React from "react"
* import { useAdminDiscountRemoveCondition } from "medusa-react"
*
* type Props = {
* discountId: string
* }
*
* const Discount = ({ discountId }: Props) => {
* const deleteCondition = useAdminDiscountRemoveCondition(
* discountId
* )
* // ...
*
* const handleDelete = (
* conditionId: string
* ) => {
* deleteCondition.mutate(conditionId, {
* onSuccess: ({ id, object, deleted }) => {
* console.log(deleted)
* }
* })
* }
*
* // ...
* }
*
* export default Discount
*
* @customNamespace Hooks.Admin.Discounts
* @category Mutations
*/
export const useAdminDiscountRemoveCondition = (
/**
* The discount's ID.
*/
discountId: string,
options?: UseMutationOptions<Response<AdminDiscountsDeleteRes>, Error, string>
) => {
@@ -27,7 +27,116 @@ export const adminDiscountKeys = {
type DiscountQueryKeys = typeof adminDiscountKeys
/**
* This hook retrieves a list of Discounts. The discounts can be filtered by fields such as `rule` or `is_dynamic`.
* The discounts can also be paginated.
*
* @example
* To list discounts:
*
* ```tsx
* import React from "react"
* import { useAdminDiscounts } from "medusa-react"
*
* const Discounts = () => {
* const { discounts, isLoading } = useAdminDiscounts()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {discounts && !discounts.length && (
* <span>No customers</span>
* )}
* {discounts && discounts.length > 0 && (
* <ul>
* {discounts.map((discount) => (
* <li key={discount.id}>{discount.code}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default Discounts
* ```
*
* To specify relations that should be retrieved within the discounts:
*
* ```tsx
* import React from "react"
* import { useAdminDiscounts } from "medusa-react"
*
* const Discounts = () => {
* const { discounts, isLoading } = useAdminDiscounts({
* expand: "rule"
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {discounts && !discounts.length && (
* <span>No customers</span>
* )}
* {discounts && discounts.length > 0 && (
* <ul>
* {discounts.map((discount) => (
* <li key={discount.id}>{discount.code}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default Discounts
* ```
*
* By default, only the first `20` records are retrieved. You can control pagination by specifying the `limit` and `offset` properties:
*
* ```tsx
* import React from "react"
* import { useAdminDiscounts } from "medusa-react"
*
* const Discounts = () => {
* const {
* discounts,
* limit,
* offset,
* isLoading
* } = useAdminDiscounts({
* expand: "rule",
* limit: 10,
* offset: 0
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {discounts && !discounts.length && (
* <span>No customers</span>
* )}
* {discounts && discounts.length > 0 && (
* <ul>
* {discounts.map((discount) => (
* <li key={discount.id}>{discount.code}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default Discounts
* ```
*
* @customNamespace Hooks.Admin.Discounts
* @category Queries
*/
export const useAdminDiscounts = (
/**
* Filters and pagination configurations to apply on the retrieved discounts.
*/
query?: AdminGetDiscountsParams,
options?: UseQueryOptionsWrapper<
Response<AdminDiscountsListRes>,
@@ -44,8 +153,43 @@ export const useAdminDiscounts = (
return { ...data, ...rest } as const
}
/**
* This hook retrieves a discount.
*
* @example
* import React from "react"
* import { useAdminDiscount } from "medusa-react"
*
* type Props = {
* discountId: string
* }
*
* const Discount = ({ discountId }: Props) => {
* const { discount, isLoading } = useAdminDiscount(
* discountId
* )
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {discount && <span>{discount.code}</span>}
* </div>
* )
* }
*
* export default Discount
*
* @customNamespace Hooks.Admin.Discounts
* @category Queries
*/
export const useAdminDiscount = (
/**
* The discount's ID.
*/
id: string,
/**
* Configurations to apply on the retrieved discount.
*/
query?: AdminGetDiscountParams,
options?: UseQueryOptionsWrapper<
Response<AdminDiscountsRes>,
@@ -62,7 +206,40 @@ export const useAdminDiscount = (
return { ...data, ...rest } as const
}
/**
* This hook adds a batch of resources to a discount condition. The type of resource depends on the type of discount condition. For example, if the discount condition's type is `products`,
* the resources being added should be products.
*
* @example
* import React from "react"
* import { useAdminGetDiscountByCode } from "medusa-react"
*
* type Props = {
* discountCode: string
* }
*
* const Discount = ({ discountCode }: Props) => {
* const { discount, isLoading } = useAdminGetDiscountByCode(
* discountCode
* )
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {discount && <span>{discount.code}</span>}
* </div>
* )
* }
*
* export default Discount
*
* @customNamespace Hooks.Admin.Discounts
* @category Queries
*/
export const useAdminGetDiscountByCode = (
/**
* The code of the discount.
*/
code: string,
options?: UseQueryOptionsWrapper<
Response<AdminDiscountsRes>,
@@ -79,9 +256,57 @@ export const useAdminGetDiscountByCode = (
return { ...data, ...rest } as const
}
/**
* This hook retries a Discount Condition's details.
*
* @example
* import React from "react"
* import { useAdminGetDiscountCondition } from "medusa-react"
*
* type Props = {
* discountId: string
* discountConditionId: string
* }
*
* const DiscountCondition = ({
* discountId,
* discountConditionId
* }: Props) => {
* const {
* discount_condition,
* isLoading
* } = useAdminGetDiscountCondition(
* discountId,
* discountConditionId
* )
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {discount_condition && (
* <span>{discount_condition.type}</span>
* )}
* </div>
* )
* }
*
* export default DiscountCondition
*
* @customNamespace Hooks.Admin.Discounts
* @category Queries
*/
export const useAdminGetDiscountCondition = (
/**
* The ID of the discount the condition belongs to.
*/
id: string,
/**
* The discount condition's ID.
*/
conditionId: string,
/**
* Configurations to apply on the retrieved discount condition.
*/
query?: AdminGetDiscountsDiscountConditionsConditionParams,
options?: UseQueryOptionsWrapper<
Response<AdminDiscountConditionsRes>,
@@ -1,2 +1,16 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Draft Order API Routes](https://docs.medusajs.com/api/admin#draft-orders).
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* A draft order is an order created manually by the admin. It allows admins to create orders without direct involvement from the customer.
*
* Related Guide: [How to manage draft orders](https://docs.medusajs.com/modules/orders/admin/manage-draft-orders).
*
* @customNamespace Hooks.Admin.Draft Orders
*/
export * from "./queries"
export * from "./mutations"
@@ -17,6 +17,46 @@ import { useMedusa } from "../../../contexts/medusa"
import { buildOptions } from "../../utils/buildOptions"
import { adminDraftOrderKeys } from "./queries"
/**
* This hook creates a Draft Order. A draft order is not transformed into an order until payment is captured.
*
* @example
* import React from "react"
* import { useAdminCreateDraftOrder } from "medusa-react"
*
* type DraftOrderData = {
* email: string
* region_id: string
* items: {
* quantity: number,
* variant_id: string
* }[]
* shipping_methods: {
* option_id: string
* price: number
* }[]
* }
*
* const CreateDraftOrder = () => {
* const createDraftOrder = useAdminCreateDraftOrder()
* // ...
*
* const handleCreate = (data: DraftOrderData) => {
* createDraftOrder.mutate(data, {
* onSuccess: ({ draft_order }) => {
* console.log(draft_order.id)
* }
* })
* }
*
* // ...
* }
*
* export default CreateDraftOrder
*
* @customNamespace Hooks.Admin.Draft Orders
* @category Mutations
*/
export const useAdminCreateDraftOrder = (
options?: UseMutationOptions<
Response<AdminDraftOrdersRes>,
@@ -33,7 +73,45 @@ export const useAdminCreateDraftOrder = (
)
}
/**
* This hook updates a Draft Order's details.
*
* @example
* import React from "react"
* import { useAdminUpdateDraftOrder } from "medusa-react"
*
* type Props = {
* draftOrderId: string
* }
*
* const DraftOrder = ({ draftOrderId }: Props) => {
* const updateDraftOrder = useAdminUpdateDraftOrder(
* draftOrderId
* )
* // ...
*
* const handleUpdate = (email: string) => {
* updateDraftOrder.mutate({
* email,
* }, {
* onSuccess: ({ draft_order }) => {
* console.log(draft_order.id)
* }
* })
* }
*
* // ...
* }
*
* export default DraftOrder
*
* @customNamespace Hooks.Admin.Draft Orders
* @category Mutations
*/
export const useAdminUpdateDraftOrder = (
/**
* The draft order's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminDraftOrdersRes>,
@@ -54,7 +132,43 @@ export const useAdminUpdateDraftOrder = (
)
}
/**
* This hook deletes a Draft Order.
*
* @example
* import React from "react"
* import { useAdminDeleteDraftOrder } from "medusa-react"
*
* type Props = {
* draftOrderId: string
* }
*
* const DraftOrder = ({ draftOrderId }: Props) => {
* const deleteDraftOrder = useAdminDeleteDraftOrder(
* draftOrderId
* )
* // ...
*
* const handleDelete = () => {
* deleteDraftOrder.mutate(void 0, {
* onSuccess: ({ id, object, deleted }) => {
* console.log(id)
* }
* })
* }
*
* // ...
* }
*
* export default DraftOrder
*
* @customNamespace Hooks.Admin.Draft Orders
* @category Mutations
*/
export const useAdminDeleteDraftOrder = (
/**
* The draft order's ID.
*/
id: string,
options?: UseMutationOptions<Response<AdminDraftOrdersDeleteRes>, Error, void>
) => {
@@ -70,7 +184,44 @@ export const useAdminDeleteDraftOrder = (
)
}
/**
* This hook capture the draft order's payment. This will also set the draft order's status to `completed` and create an order from the draft order. The payment is captured through Medusa's system payment,
* which is manual payment that isn't integrated with any third-party payment provider. It is assumed that the payment capturing is handled manually by the admin.
*
* @example
* import React from "react"
* import { useAdminDraftOrderRegisterPayment } from "medusa-react"
*
* type Props = {
* draftOrderId: string
* }
*
* const DraftOrder = ({ draftOrderId }: Props) => {
* const registerPayment = useAdminDraftOrderRegisterPayment(
* draftOrderId
* )
* // ...
*
* const handlePayment = () => {
* registerPayment.mutate(void 0, {
* onSuccess: ({ order }) => {
* console.log(order.id)
* }
* })
* }
*
* // ...
* }
*
* export default DraftOrder
*
* @customNamespace Hooks.Admin.Draft Orders
* @category Mutations
*/
export const useAdminDraftOrderRegisterPayment = (
/**
* The draft order's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminPostDraftOrdersDraftOrderRegisterPaymentRes>,
@@ -86,7 +237,45 @@ export const useAdminDraftOrderRegisterPayment = (
)
}
/**
* This hook creates a Line Item in the Draft Order.
*
* @example
* import React from "react"
* import { useAdminDraftOrderAddLineItem } from "medusa-react"
*
* type Props = {
* draftOrderId: string
* }
*
* const DraftOrder = ({ draftOrderId }: Props) => {
* const addLineItem = useAdminDraftOrderAddLineItem(
* draftOrderId
* )
* // ...
*
* const handleAdd = (quantity: number) => {
* addLineItem.mutate({
* quantity,
* }, {
* onSuccess: ({ draft_order }) => {
* console.log(draft_order.cart)
* }
* })
* }
*
* // ...
* }
*
* export default DraftOrder
*
* @customNamespace Hooks.Admin.Draft Orders
* @category Mutations
*/
export const useAdminDraftOrderAddLineItem = (
/**
* The draft order's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminDraftOrdersRes>,
@@ -103,7 +292,45 @@ export const useAdminDraftOrderAddLineItem = (
)
}
/**
* This hook deletes a Line Item from a Draft Order.
*
* @typeParamDefinition string - The ID of the line item to remove.
*
* @example
* import React from "react"
* import { useAdminDraftOrderRemoveLineItem } from "medusa-react"
*
* type Props = {
* draftOrderId: string
* }
*
* const DraftOrder = ({ draftOrderId }: Props) => {
* const deleteLineItem = useAdminDraftOrderRemoveLineItem(
* draftOrderId
* )
* // ...
*
* const handleDelete = (itemId: string) => {
* deleteLineItem.mutate(itemId, {
* onSuccess: ({ draft_order }) => {
* console.log(draft_order.cart)
* }
* })
* }
*
* // ...
* }
*
* export default DraftOrder
*
* @customNamespace Hooks.Admin.Draft Orders
* @category Mutations
*/
export const useAdminDraftOrderRemoveLineItem = (
/**
* The draft order's ID.
*/
id: string,
options?: UseMutationOptions<Response<AdminDraftOrdersRes>, Error, string>
) => {
@@ -115,12 +342,60 @@ export const useAdminDraftOrderRemoveLineItem = (
)
}
/**
* The details to update of the line item.
*/
export type AdminDraftOrderUpdateLineItemReq = AdminPostDraftOrdersDraftOrderLineItemsItemReq & {
/**
* The line item's ID to update.
*/
item_id: string
}
/**
* This hook updates a Line Item in a Draft Order.
*
* @example
* import React from "react"
* import { useAdminDraftOrderUpdateLineItem } from "medusa-react"
*
* type Props = {
* draftOrderId: string
* }
*
* const DraftOrder = ({ draftOrderId }: Props) => {
* const updateLineItem = useAdminDraftOrderUpdateLineItem(
* draftOrderId
* )
* // ...
*
* const handleUpdate = (
* itemId: string,
* quantity: number
* ) => {
* updateLineItem.mutate({
* item_id: itemId,
* quantity,
* })
* }
*
* // ...
* }
*
* export default DraftOrder
*
* @customNamespace Hooks.Admin.Draft Orders
* @category Mutations
*/
export const useAdminDraftOrderUpdateLineItem = (
/**
* The draft order's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminDraftOrdersRes>,
Error,
AdminPostDraftOrdersDraftOrderLineItemsItemReq & { item_id: string }
AdminDraftOrderUpdateLineItemReq
>
) => {
const { client } = useMedusa()
@@ -129,7 +404,7 @@ export const useAdminDraftOrderUpdateLineItem = (
({
item_id,
...payload
}: AdminPostDraftOrdersDraftOrderLineItemsItemReq & { item_id: string }) =>
}: AdminDraftOrderUpdateLineItemReq) =>
client.admin.draftOrders.updateLineItem(id, item_id, payload),
buildOptions(queryClient, adminDraftOrderKeys.detail(id), options)
)
@@ -17,7 +17,83 @@ export const adminDraftOrderKeys = queryKeysFactory(
type DraftOrderQueryKeys = typeof adminDraftOrderKeys
/**
* This hook retrieves an list of Draft Orders. The draft orders can be filtered by parameters such as `query`. The draft orders can also paginated.
*
* @example
* To list draft orders:
*
* ```tsx
* import React from "react"
* import { useAdminDraftOrders } from "medusa-react"
*
* const DraftOrders = () => {
* const { draft_orders, isLoading } = useAdminDraftOrders()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {draft_orders && !draft_orders.length && (
* <span>No Draft Orders</span>
* )}
* {draft_orders && draft_orders.length > 0 && (
* <ul>
* {draft_orders.map((order) => (
* <li key={order.id}>{order.display_id}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default DraftOrders
* ```
*
* By default, only the first `50` records are retrieved. You can control pagination by specifying the `limit` and `offset` properties:
*
* ```tsx
* import React from "react"
* import { useAdminDraftOrders } from "medusa-react"
*
* const DraftOrders = () => {
* const {
* draft_orders,
* limit,
* offset,
* isLoading
* } = useAdminDraftOrders({
* limit: 20,
* offset: 0
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {draft_orders && !draft_orders.length && (
* <span>No Draft Orders</span>
* )}
* {draft_orders && draft_orders.length > 0 && (
* <ul>
* {draft_orders.map((order) => (
* <li key={order.id}>{order.display_id}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default DraftOrders
* ```
*
* @customNamespace Hooks.Admin.Draft Orders
* @category Queries
*/
export const useAdminDraftOrders = (
/**
* Filters and pagination configurations to apply on the retrieved draft orders.
*/
query?: AdminGetDraftOrdersParams,
options?: UseQueryOptionsWrapper<
Response<AdminDraftOrdersListRes>,
@@ -34,7 +110,41 @@ export const useAdminDraftOrders = (
return { ...data, ...rest } as const
}
/**
* This hook retrieves a Draft Order's details.
*
* @example
* import React from "react"
* import { useAdminDraftOrder } from "medusa-react"
*
* type Props = {
* draftOrderId: string
* }
*
* const DraftOrder = ({ draftOrderId }: Props) => {
* const {
* draft_order,
* isLoading,
* } = useAdminDraftOrder(draftOrderId)
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {draft_order && <span>{draft_order.display_id}</span>}
*
* </div>
* )
* }
*
* export default DraftOrder
*
* @customNamespace Hooks.Admin.Draft Orders
* @category Queries
*/
export const useAdminDraftOrder = (
/**
* The draft order's ID.
*/
id: string,
options?: UseQueryOptionsWrapper<
Response<AdminDraftOrdersRes>,
@@ -1,2 +1,17 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Gift Card API Routes](https://docs.medusajs.com/api/admin#gift-cards).
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* Admins can create gift cards and send them directly to customers, specifying options like their balance, region, and more.
* These gift cards are different than the saleable gift cards in a store, which are created and managed through {@link Hooks.Admin.Products.useAdminCreateProduct | useAdminCreateProduct}.
*
* Related Guide: [How to manage gift cards](https://docs.medusajs.com/modules/gift-cards/admin/manage-gift-cards#manage-custom-gift-cards).
*
* @customNamespace Hooks.Admin.Gift Cards
*/
export * from "./queries"
export * from "./mutations"
@@ -14,6 +14,39 @@ import { useMedusa } from "../../../contexts/medusa"
import { buildOptions } from "../../utils/buildOptions"
import { adminGiftCardKeys } from "./queries"
/**
* This hook creates a gift card that can redeemed by its unique code. The Gift Card is only valid within one region.
*
* @example
* import React from "react"
* import { useAdminCreateGiftCard } from "medusa-react"
*
* const CreateCustomGiftCards = () => {
* const createGiftCard = useAdminCreateGiftCard()
* // ...
*
* const handleCreate = (
* regionId: string,
* value: number
* ) => {
* createGiftCard.mutate({
* region_id: regionId,
* value,
* }, {
* onSuccess: ({ gift_card }) => {
* console.log(gift_card.id)
* }
* })
* }
*
* // ...
* }
*
* export default CreateCustomGiftCards
*
* @customNamespace Hooks.Admin.Gift Cards
* @category Mutations
*/
export const useAdminCreateGiftCard = (
options?: UseMutationOptions<
Response<AdminGiftCardsRes>,
@@ -29,7 +62,45 @@ export const useAdminCreateGiftCard = (
)
}
/**
* This hook updates a gift card's details.
*
* @example
* import React from "react"
* import { useAdminUpdateGiftCard } from "medusa-react"
*
* type Props = {
* customGiftCardId: string
* }
*
* const CustomGiftCard = ({ customGiftCardId }: Props) => {
* const updateGiftCard = useAdminUpdateGiftCard(
* customGiftCardId
* )
* // ...
*
* const handleUpdate = (regionId: string) => {
* updateGiftCard.mutate({
* region_id: regionId,
* }, {
* onSuccess: ({ gift_card }) => {
* console.log(gift_card.id)
* }
* })
* }
*
* // ...
* }
*
* export default CustomGiftCard
*
* @customNamespace Hooks.Admin.Gift Cards
* @category Mutations
*/
export const useAdminUpdateGiftCard = (
/**
* The gift card's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminGiftCardsRes>,
@@ -51,7 +122,43 @@ export const useAdminUpdateGiftCard = (
)
}
/**
* This hook deletes a gift card. Once deleted, it can't be used by customers.
*
* @example
* import React from "react"
* import { useAdminDeleteGiftCard } from "medusa-react"
*
* type Props = {
* customGiftCardId: string
* }
*
* const CustomGiftCard = ({ customGiftCardId }: Props) => {
* const deleteGiftCard = useAdminDeleteGiftCard(
* customGiftCardId
* )
* // ...
*
* const handleDelete = () => {
* deleteGiftCard.mutate(void 0, {
* onSuccess: ({ id, object, deleted}) => {
* console.log(id)
* }
* })
* }
*
* // ...
* }
*
* export default CustomGiftCard
*
* @customNamespace Hooks.Admin.Gift Cards
* @category Mutations
*/
export const useAdminDeleteGiftCard = (
/**
* The gift card's ID.
*/
id: string,
options?: UseMutationOptions<Response<AdminGiftCardsDeleteRes>, Error, void>
) => {
@@ -15,7 +15,84 @@ export const adminGiftCardKeys = queryKeysFactory(ADMIN_GIFT_CARDS_QUERY_KEY)
type GiftCardQueryKeys = typeof adminGiftCardKeys
/**
* This hook retrieves a list of gift cards. The gift cards can be filtered by fields such as `q` passed in the `query`
* parameter. The gift cards can also paginated.
*
* @example
* To list gift cards:
*
* ```tsx
* import React from "react"
* import { useAdminGiftCards } from "medusa-react"
*
* const CustomGiftCards = () => {
* const { gift_cards, isLoading } = useAdminGiftCards()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {gift_cards && !gift_cards.length && (
* <span>No custom gift cards...</span>
* )}
* {gift_cards && gift_cards.length > 0 && (
* <ul>
* {gift_cards.map((giftCard) => (
* <li key={giftCard.id}>{giftCard.code}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default CustomGiftCards
* ```
*
* By default, only the first `50` records are retrieved. You can control pagination by specifying the `limit` and `offset` properties:
*
* ```tsx
* import React from "react"
* import { useAdminGiftCards } from "medusa-react"
*
* const CustomGiftCards = () => {
* const {
* gift_cards,
* limit,
* offset,
* isLoading
* } = useAdminGiftCards({
* limit: 20,
* offset: 0
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {gift_cards && !gift_cards.length && (
* <span>No custom gift cards...</span>
* )}
* {gift_cards && gift_cards.length > 0 && (
* <ul>
* {gift_cards.map((giftCard) => (
* <li key={giftCard.id}>{giftCard.code}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default CustomGiftCards
* ```
*
* @customNamespace Hooks.Admin.Gift Cards
* @category Queries
*/
export const useAdminGiftCards = (
/**
* Filters and pagination configurations to apply on the retrieved gift cards.
*/
query?: AdminGetGiftCardsParams,
options?: UseQueryOptionsWrapper<
Response<AdminGiftCardsListRes>,
@@ -32,7 +109,37 @@ export const useAdminGiftCards = (
return { ...data, ...rest } as const
}
/**
* This hook retrieves a gift card's details.
*
* @example
* import React from "react"
* import { useAdminGiftCard } from "medusa-react"
*
* type Props = {
* giftCardId: string
* }
*
* const CustomGiftCard = ({ giftCardId }: Props) => {
* const { gift_card, isLoading } = useAdminGiftCard(giftCardId)
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {gift_card && <span>{gift_card.code}</span>}
* </div>
* )
* }
*
* export default CustomGiftCard
*
* @customNamespace Hooks.Admin.Gift Cards
* @category Queries
*/
export const useAdminGiftCard = (
/**
* The gift card's ID.
*/
id: string,
options?: UseQueryOptionsWrapper<
Response<AdminGiftCardsRes>,
@@ -1,2 +1,19 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Inventory Item API Routes](https://docs.medusajs.com/api/admin#inventory-items).
* To use these hooks, make sure to install the
* [@medusajs/inventory](https://docs.medusajs.com/modules/multiwarehouse/install-modules#inventory-module) module in your Medusa backend.
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* Inventory items, provided by the [Inventory Module](https://docs.medusajs.com/modules/multiwarehouse/inventory-module), can be
* used to manage the inventory of saleable items in your store.
*
* Related Guide: [How to manage inventory items](https://docs.medusajs.com/modules/multiwarehouse/admin/manage-inventory-items).
*
* @customNamespace Hooks.Admin.Inventory Items
*/
export * from "./queries"
export * from "./mutations"
@@ -17,9 +17,35 @@ import { useMedusa } from "../../../contexts"
import { buildOptions } from "../../utils/buildOptions"
import { adminInventoryItemsKeys } from "./queries"
// inventory item
// create inventory item
/**
* This hook creates an Inventory Item for a product variant.
*
* @example
* import React from "react"
* import { useAdminCreateInventoryItem } from "medusa-react"
*
* const CreateInventoryItem = () => {
* const createInventoryItem = useAdminCreateInventoryItem()
* // ...
*
* const handleCreate = (variantId: string) => {
* createInventoryItem.mutate({
* variant_id: variantId,
* }, {
* onSuccess: ({ inventory_item }) => {
* console.log(inventory_item.id)
* }
* })
* }
*
* // ...
* }
*
* export default CreateInventoryItem
*
* @customNamespace Hooks.Admin.Inventory Items
* @category Mutations
*/
export const useAdminCreateInventoryItem = (
options?: UseMutationOptions<
Response<AdminInventoryItemsRes>,
@@ -42,8 +68,45 @@ export const useAdminCreateInventoryItem = (
}
// update inventory item
/**
* This hook updates an Inventory Item's details.
*
* @example
* import React from "react"
* import { useAdminUpdateInventoryItem } from "medusa-react"
*
* type Props = {
* inventoryItemId: string
* }
*
* const InventoryItem = ({ inventoryItemId }: Props) => {
* const updateInventoryItem = useAdminUpdateInventoryItem(
* inventoryItemId
* )
* // ...
*
* const handleUpdate = (origin_country: string) => {
* updateInventoryItem.mutate({
* origin_country,
* }, {
* onSuccess: ({ inventory_item }) => {
* console.log(inventory_item.origin_country)
* }
* })
* }
*
* // ...
* }
*
* export default InventoryItem
*
* @customNamespace Hooks.Admin.Inventory Items
* @category Mutations
*/
export const useAdminUpdateInventoryItem = (
/**
* The inventory item's ID.
*/
inventoryItemId: string,
options?: UseMutationOptions<
Response<AdminInventoryItemsRes>,
@@ -65,8 +128,39 @@ export const useAdminUpdateInventoryItem = (
)
}
// delete inventory item
/**
* This hook deletes an Inventory Item. This does not delete the associated product variant.
*
* @example
* import React from "react"
* import { useAdminDeleteInventoryItem } from "medusa-react"
*
* type Props = {
* inventoryItemId: string
* }
*
* const InventoryItem = ({ inventoryItemId }: Props) => {
* const deleteInventoryItem = useAdminDeleteInventoryItem(
* inventoryItemId
* )
* // ...
*
* const handleDelete = () => {
* deleteInventoryItem.mutate()
* }
*
* // ...
* }
*
* export default InventoryItem
*
* @customNamespace Hooks.Admin.Inventory Items
* @category Mutations
*/
export const useAdminDeleteInventoryItem = (
/**
* The inventory item's ID.
*/
inventoryItemId: string,
options?: UseMutationOptions<
Response<AdminInventoryItemsDeleteRes>,
@@ -87,15 +181,61 @@ export const useAdminDeleteInventoryItem = (
)
}
// location level
export type AdminUpdateLocationLevelReq = AdminPostInventoryItemsItemLocationLevelsLevelReq & {
/**
* The ID of the location level to update.
*/
stockLocationId: string
}
/**
* This hook updates a location level's details for a given inventory item.
*
* @example
* import React from "react"
* import { useAdminUpdateLocationLevel } from "medusa-react"
*
* type Props = {
* inventoryItemId: string
* }
*
* const InventoryItem = ({ inventoryItemId }: Props) => {
* const updateLocationLevel = useAdminUpdateLocationLevel(
* inventoryItemId
* )
* // ...
*
* const handleUpdate = (
* stockLocationId: string,
* stockedQuantity: number
* ) => {
* updateLocationLevel.mutate({
* stockLocationId,
* stocked_quantity: stockedQuantity,
* }, {
* onSuccess: ({ inventory_item }) => {
* console.log(inventory_item.id)
* }
* })
* }
*
* // ...
* }
*
* export default InventoryItem
*
* @customNamespace Hooks.Admin.Inventory Items
* @category Mutations
*/
export const useAdminUpdateLocationLevel = (
/**
* The inventory item's ID.
*/
inventoryItemId: string,
options?: UseMutationOptions<
Response<AdminInventoryItemsRes>,
Error,
AdminPostInventoryItemsItemLocationLevelsLevelReq & {
stockLocationId: string
}
AdminUpdateLocationLevelReq
>
) => {
const { client } = useMedusa()
@@ -103,9 +243,7 @@ export const useAdminUpdateLocationLevel = (
return useMutation(
(
payload: AdminPostInventoryItemsItemLocationLevelsLevelReq & {
stockLocationId: string
}
payload: AdminUpdateLocationLevelReq
) =>
client.admin.inventoryItems.updateLocationLevel(
inventoryItemId,
@@ -126,7 +264,43 @@ export const useAdminUpdateLocationLevel = (
)
}
/**
* This hook deletes a location level of an Inventory Item.
*
* @typeParamDefinition string - The ID of the location level to delete.
*
* @example
* import React from "react"
* import { useAdminDeleteLocationLevel } from "medusa-react"
*
* type Props = {
* inventoryItemId: string
* }
*
* const InventoryItem = ({ inventoryItemId }: Props) => {
* const deleteLocationLevel = useAdminDeleteLocationLevel(
* inventoryItemId
* )
* // ...
*
* const handleDelete = (
* locationId: string
* ) => {
* deleteLocationLevel.mutate(locationId)
* }
*
* // ...
* }
*
* export default InventoryItem
*
* @customNamespace Hooks.Admin.Inventory Items
* @category Mutations
*/
export const useAdminDeleteLocationLevel = (
/**
* The inventory item's ID.
*/
inventoryItemId: string,
options?: UseMutationOptions<Response<AdminInventoryItemsRes>, Error, string>
) => {
@@ -150,7 +324,49 @@ export const useAdminDeleteLocationLevel = (
)
}
/**
* This hook creates a Location Level for a given Inventory Item.
*
* @example
* import React from "react"
* import { useAdminCreateLocationLevel } from "medusa-react"
*
* type Props = {
* inventoryItemId: string
* }
*
* const InventoryItem = ({ inventoryItemId }: Props) => {
* const createLocationLevel = useAdminCreateLocationLevel(
* inventoryItemId
* )
* // ...
*
* const handleCreateLocationLevel = (
* locationId: string,
* stockedQuantity: number
* ) => {
* createLocationLevel.mutate({
* location_id: locationId,
* stocked_quantity: stockedQuantity,
* }, {
* onSuccess: ({ inventory_item }) => {
* console.log(inventory_item.id)
* }
* })
* }
*
* // ...
* }
*
* export default InventoryItem
*
* @customNamespace Hooks.Admin.Inventory Items
* @category Mutations
*/
export const useAdminCreateLocationLevel = (
/**
* The inventory item's ID.
*/
inventoryItemId: string,
options?: UseMutationOptions<
Response<AdminInventoryItemsRes>,
@@ -21,7 +21,91 @@ export const adminInventoryItemsKeys = queryKeysFactory(
type InventoryItemsQueryKeys = typeof adminInventoryItemsKeys
/**
* This hook retrieves a list of inventory items. The inventory items can be filtered by fields such as `q` or `location_id` passed in the `query` parameter.
* The inventory items can also be paginated.
*
* @example
* To list inventory items:
*
* ```tsx
* import React from "react"
* import { useAdminInventoryItems } from "medusa-react"
*
* function InventoryItems() {
* const {
* inventory_items,
* isLoading
* } = useAdminInventoryItems()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {inventory_items && !inventory_items.length && (
* <span>No Items</span>
* )}
* {inventory_items && inventory_items.length > 0 && (
* <ul>
* {inventory_items.map(
* (item) => (
* <li key={item.id}>{item.id}</li>
* )
* )}
* </ul>
* )}
* </div>
* )
* }
*
* export default InventoryItems
* ```
*
* By default, only the first `20` records are retrieved. You can control pagination by specifying the `limit` and `offset` properties:
*
* ```tsx
* import React from "react"
* import { useAdminInventoryItems } from "medusa-react"
*
* function InventoryItems() {
* const {
* inventory_items,
* limit,
* offset,
* isLoading
* } = useAdminInventoryItems({
* limit: 10,
* offset: 0
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {inventory_items && !inventory_items.length && (
* <span>No Items</span>
* )}
* {inventory_items && inventory_items.length > 0 && (
* <ul>
* {inventory_items.map(
* (item) => (
* <li key={item.id}>{item.id}</li>
* )
* )}
* </ul>
* )}
* </div>
* )
* }
*
* export default InventoryItems
* ```
*
* @customNamespace Hooks.Admin.Inventory Items
* @category Queries
*/
export const useAdminInventoryItems = (
/**
* Filters and pagination configurations applied on the retrieved inventory items.
*/
query?: AdminGetInventoryItemsParams,
options?: UseQueryOptionsWrapper<
Response<AdminInventoryItemsListWithVariantsAndLocationLevelsRes>,
@@ -40,8 +124,46 @@ export const useAdminInventoryItems = (
return { ...data, ...rest } as const
}
/**
* This hook retrieves an Inventory Item's details.
*
* @example
* import React from "react"
* import { useAdminInventoryItem } from "medusa-react"
*
* type Props = {
* inventoryItemId: string
* }
*
* const InventoryItem = ({ inventoryItemId }: Props) => {
* const {
* inventory_item,
* isLoading
* } = useAdminInventoryItem(inventoryItemId)
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {inventory_item && (
* <span>{inventory_item.sku}</span>
* )}
* </div>
* )
* }
*
* export default InventoryItem
*
* @customNamespace Hooks.Admin.Inventory Items
* @category Queries
*/
export const useAdminInventoryItem = (
/**
* The inventory item's ID.
*/
inventoryItemId: string,
/**
* Configurations applied on the retrieved inventory item.
*/
query?: AdminGetStockLocationsParams,
options?: UseQueryOptionsWrapper<
Response<AdminInventoryItemsRes>,
@@ -60,8 +182,53 @@ export const useAdminInventoryItem = (
return { ...data, ...rest } as const
}
/**
* This hook retrieves a list of inventory levels of an inventory item. The inventory levels can be filtered by fields
* such as `location_id` passed in the `query` parameter.
*
* @example
* import React from "react"
* import {
* useAdminInventoryItemLocationLevels,
* } from "medusa-react"
*
* type Props = {
* inventoryItemId: string
* }
*
* const InventoryItem = ({ inventoryItemId }: Props) => {
* const {
* inventory_item,
* isLoading,
* } = useAdminInventoryItemLocationLevels(inventoryItemId)
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {inventory_item && (
* <ul>
* {inventory_item.location_levels.map((level) => (
* <span key={level.id}>{level.stocked_quantity}</span>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default InventoryItem
*
* @customNamespace Hooks.Admin.Inventory Items
* @category Queries
*/
export const useAdminInventoryItemLocationLevels = (
/**
* The ID of the inventory item that the location levels belong to.
*/
inventoryItemId: string,
/**
* Filters to apply on the retrieved location levels.
*/
query?: AdminGetInventoryItemsItemLocationLevelsParams,
options?: UseQueryOptionsWrapper<
Response<AdminInventoryItemsLocationLevelsRes>,
@@ -1,2 +1,16 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Invite API Routes](https://docs.medusajs.com/api/admin#invites).
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* An admin can invite new users to manage their team. This would allow new users to authenticate as admins and perform admin functionalities.
*
* Related Guide: [How to manage invites](https://docs.medusajs.com/modules/users/admin/manage-invites).
*
* @customNamespace Hooks.Admin.Invites
*/
export * from "./queries"
export * from "./mutations"
@@ -12,6 +12,46 @@ import { useMedusa } from "../../../contexts/medusa"
import { buildOptions } from "../../utils/buildOptions"
import { adminInviteKeys } from "./queries"
/**
* This hook accepts an Invite. This will also delete the invite and create a new user that can log in and perform admin functionalities.
* The user will have the email associated with the invite, and the password provided in the mutation function's parameter.
*
* @example
* import React from "react"
* import { useAdminAcceptInvite } from "medusa-react"
*
* const AcceptInvite = () => {
* const acceptInvite = useAdminAcceptInvite()
* // ...
*
* const handleAccept = (
* token: string,
* firstName: string,
* lastName: string,
* password: string
* ) => {
* acceptInvite.mutate({
* token,
* user: {
* first_name: firstName,
* last_name: lastName,
* password,
* },
* }, {
* onSuccess: () => {
* // invite accepted successfully.
* }
* })
* }
*
* // ...
* }
*
* export default AcceptInvite
*
* @customNamespace Hooks.Admin.Invites
* @category Mutations
*/
export const useAdminAcceptInvite = (
options?: UseMutationOptions<
Response<void>,
@@ -29,7 +69,43 @@ export const useAdminAcceptInvite = (
)
}
/**
* This hook resends an invite. This renews the expiry date by seven days and generates a new token for the invite. It also triggers the `invite.created` event,
* so if you have a Notification Provider installed that handles this event, a notification should be sent to the email associated with the
* invite to allow them to accept the invite.
*
* @example
* import React from "react"
* import { useAdminResendInvite } from "medusa-react"
*
* type Props = {
* inviteId: string
* }
*
* const ResendInvite = ({ inviteId }: Props) => {
* const resendInvite = useAdminResendInvite(inviteId)
* // ...
*
* const handleResend = () => {
* resendInvite.mutate(void 0, {
* onSuccess: () => {
* // invite resent successfully
* }
* })
* }
*
* // ...
* }
*
* export default ResendInvite
*
* @customNamespace Hooks.Admin.Invites
* @category Mutations
*/
export const useAdminResendInvite = (
/**
* The invite's ID.
*/
id: string,
options?: UseMutationOptions
) => {
@@ -49,7 +125,41 @@ export const useAdminCreateInvite = (
)
}
/**
* This hook deletes an invite. Only invites that weren't accepted can be deleted.
*
* @example
* import React from "react"
* import { useAdminDeleteInvite } from "medusa-react"
*
* type Props = {
* inviteId: string
* }
*
* const DeleteInvite = ({ inviteId }: Props) => {
* const deleteInvite = useAdminDeleteInvite(inviteId)
* // ...
*
* const handleDelete = () => {
* deleteInvite.mutate(void 0, {
* onSuccess: ({ id, object, deleted }) => {
* console.log(id)
* }
* })
* }
*
* // ...
* }
*
* export default Invite
*
* @customNamespace Hooks.Admin.Invites
* @category Mutations
*/
export const useAdminDeleteInvite = (
/**
* The invite's ID.
*/
id: string,
options?: UseMutationOptions<Response<AdminInviteDeleteRes>, Error, void>
) => {
@@ -11,6 +11,38 @@ export const adminInviteKeys = queryKeysFactory(ADMIN_INVITES_QUERY_KEY)
type InviteQueryKeys = typeof adminInviteKeys
/**
* This hook retrieves a list of invites.
*
* @example
* import React from "react"
* import { useAdminInvites } from "medusa-react"
*
* const Invites = () => {
* const { invites, isLoading } = useAdminInvites()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {invites && !invites.length && (
* <span>No Invites</span>)
* }
* {invites && invites.length > 0 && (
* <ul>
* {invites.map((invite) => (
* <li key={invite.id}>{invite.user_email}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default Invites
*
* @customNamespace Hooks.Admin.Invites
* @category Queries
*/
export const useAdminInvites = (
options?: UseQueryOptionsWrapper<
Response<AdminListInvitesRes>,
@@ -1,2 +1,14 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Note API Routes](https://docs.medusajs.com/api/admin#notes).
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* Notes are created by admins and can be associated with any resource. For example, an admin can add a note to an order for additional details or remarks.
*
* @customNamespace Hooks.Admin.Notes
*/
export * from "./queries"
export * from "./mutations"
@@ -14,6 +14,37 @@ import { useMedusa } from "../../../contexts/medusa"
import { buildOptions } from "../../utils/buildOptions"
import { adminNoteKeys } from "./queries"
/**
* This hook creates a Note which can be associated with any resource.
*
* @example
* import React from "react"
* import { useAdminCreateNote } from "medusa-react"
*
* const CreateNote = () => {
* const createNote = useAdminCreateNote()
* // ...
*
* const handleCreate = () => {
* createNote.mutate({
* resource_id: "order_123",
* resource_type: "order",
* value: "We delivered this order"
* }, {
* onSuccess: ({ note }) => {
* console.log(note.id)
* }
* })
* }
*
* // ...
* }
*
* export default CreateNote
*
* @customNamespace Hooks.Admin.Notes
* @category Mutations
*/
export const useAdminCreateNote = (
options?: UseMutationOptions<
Response<AdminNotesRes>,
@@ -29,7 +60,45 @@ export const useAdminCreateNote = (
)
}
/**
* This hook updates a Note's details.
*
* @example
* import React from "react"
* import { useAdminUpdateNote } from "medusa-react"
*
* type Props = {
* noteId: string
* }
*
* const Note = ({ noteId }: Props) => {
* const updateNote = useAdminUpdateNote(noteId)
* // ...
*
* const handleUpdate = (
* value: string
* ) => {
* updateNote.mutate({
* value
* }, {
* onSuccess: ({ note }) => {
* console.log(note.value)
* }
* })
* }
*
* // ...
* }
*
* export default Note
*
* @customNamespace Hooks.Admin.Notes
* @category Mutations
*/
export const useAdminUpdateNote = (
/**
* The note's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminNotesRes>,
@@ -50,7 +119,37 @@ export const useAdminUpdateNote = (
)
}
/**
* This hook deletes a Note.
*
* @example
* import React from "react"
* import { useAdminDeleteNote } from "medusa-react"
*
* type Props = {
* noteId: string
* }
*
* const Note = ({ noteId }: Props) => {
* const deleteNote = useAdminDeleteNote(noteId)
* // ...
*
* const handleDelete = () => {
* deleteNote.mutate()
* }
*
* // ...
* }
*
* export default Note
*
* @customNamespace Hooks.Admin.Notes
* @category Mutations
*/
export const useAdminDeleteNote = (
/**
* The note's ID.
*/
id: string,
options?: UseMutationOptions<Response<AdminNotesDeleteRes>, Error, void>
) => {
@@ -15,7 +15,80 @@ export const adminNoteKeys = queryKeysFactory(ADMIN_NOTE_QUERY_KEY)
type NoteQueryKeys = typeof adminNoteKeys
/**
* This hook retrieves a list of notes. The notes can be filtered by fields such as `resource_id` passed in
* the `query` parameter. The notes can also be paginated.
*
* @example
* To list notes:
*
* ```tsx
* import React from "react"
* import { useAdminNotes } from "medusa-react"
*
* const Notes = () => {
* const { notes, isLoading } = useAdminNotes()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {notes && !notes.length && <span>No Notes</span>}
* {notes && notes.length > 0 && (
* <ul>
* {notes.map((note) => (
* <li key={note.id}>{note.resource_type}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default Notes
* ```
*
* By default, only the first `50` records are retrieved. You can control pagination by specifying the `limit` and `offset` properties:
*
* ```tsx
* import React from "react"
* import { useAdminNotes } from "medusa-react"
*
* const Notes = () => {
* const {
* notes,
* limit,
* offset,
* isLoading
* } = useAdminNotes({
* limit: 40,
* offset: 0
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {notes && !notes.length && <span>No Notes</span>}
* {notes && notes.length > 0 && (
* <ul>
* {notes.map((note) => (
* <li key={note.id}>{note.resource_type}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default Notes
* ```
*
* @customNamespace Hooks.Admin.Notes
* @category Queries
*/
export const useAdminNotes = (
/**
* Filters and pagination configurations applied on retrieved notes.
*/
query?: AdminGetNotesParams,
options?: UseQueryOptionsWrapper<
Response<AdminNotesListRes>,
@@ -32,7 +105,37 @@ export const useAdminNotes = (
return { ...data, ...rest } as const
}
/**
* This hook retrieves a note's details.
*
* @example
* import React from "react"
* import { useAdminNote } from "medusa-react"
*
* type Props = {
* noteId: string
* }
*
* const Note = ({ noteId }: Props) => {
* const { note, isLoading } = useAdminNote(noteId)
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {note && <span>{note.resource_type}</span>}
* </div>
* )
* }
*
* export default Note
*
* @customNamespace Hooks.Admin.Notes
* @category Queries
*/
export const useAdminNote = (
/**
* The note's ID.
*/
id: string,
options?: UseQueryOptionsWrapper<
Response<AdminNotesRes>,
@@ -1,2 +1,15 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Notification API Routes](https://docs.medusajs.com/api/admin#notifications).
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* Notifications are sent to customers to inform them of new updates. For example, a notification can be sent to the customer when their order is place or its state is updated.
* The notification's type, such as an email or SMS, is determined by the notification provider installed on the Medusa backend.
*
* @customNamespace Hooks.Admin.Notifications
*/
export * from "./queries"
export * from "./mutations"
@@ -12,7 +12,43 @@ import { useMedusa } from "../../../contexts/medusa"
import { buildOptions } from "../../utils/buildOptions"
import { adminNotificationKeys } from "./queries"
/**
* This hook resends a previously sent notifications, with the same data but optionally to a different address.
*
* @example
* import React from "react"
* import { useAdminResendNotification } from "medusa-react"
*
* type Props = {
* notificationId: string
* }
*
* const Notification = ({ notificationId }: Props) => {
* const resendNotification = useAdminResendNotification(
* notificationId
* )
* // ...
*
* const handleResend = () => {
* resendNotification.mutate({}, {
* onSuccess: ({ notification }) => {
* console.log(notification.id)
* }
* })
* }
*
* // ...
* }
*
* export default Notification
*
* @customNamespace Hooks.Admin.Notifications
* @category Mutations
*/
export const useAdminResendNotification = (
/**
* The ID of the notification.
*/
id: string,
options?: UseMutationOptions<
Response<AdminNotificationsRes>,
@@ -16,7 +16,116 @@ export const adminNotificationKeys = queryKeysFactory(
type NotificationQueryKeys = typeof adminNotificationKeys
/**
* This hook retrieves a list of notifications. The notifications can be filtered by fields such as `event_name` or `resource_type` passed in the `query` parameter.
* The notifications can also be paginated.
*
* @example
* To list notifications:
*
* ```tsx
* import React from "react"
* import { useAdminNotifications } from "medusa-react"
*
* const Notifications = () => {
* const { notifications, isLoading } = useAdminNotifications()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {notifications && !notifications.length && (
* <span>No Notifications</span>
* )}
* {notifications && notifications.length > 0 && (
* <ul>
* {notifications.map((notification) => (
* <li key={notification.id}>{notification.to}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default Notifications
* ```
*
* To specify relations that should be retrieved within the notifications:
*
* ```tsx
* import React from "react"
* import { useAdminNotifications } from "medusa-react"
*
* const Notifications = () => {
* const { notifications, isLoading } = useAdminNotifications({
* expand: "provider"
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {notifications && !notifications.length && (
* <span>No Notifications</span>
* )}
* {notifications && notifications.length > 0 && (
* <ul>
* {notifications.map((notification) => (
* <li key={notification.id}>{notification.to}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default Notifications
* ```
*
* By default, only the first `50` records are retrieved. You can control pagination by specifying the `limit` and `offset` properties:
*
* ```tsx
* import React from "react"
* import { useAdminNotifications } from "medusa-react"
*
* const Notifications = () => {
* const {
* notifications,
* limit,
* offset,
* isLoading
* } = useAdminNotifications({
* expand: "provider",
* limit: 20,
* offset: 0
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {notifications && !notifications.length && (
* <span>No Notifications</span>
* )}
* {notifications && notifications.length > 0 && (
* <ul>
* {notifications.map((notification) => (
* <li key={notification.id}>{notification.to}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default Notifications
* ```
*
* @customNamespace Hooks.Admin.Notifications
* @category Queries
*/
export const useAdminNotifications = (
/**
* Filters and pagination configurations applied to the retrieved notifications.
*/
query?: AdminGetNotificationsParams,
options?: UseQueryOptionsWrapper<
Response<AdminNotificationsListRes>,
@@ -1,2 +1,16 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Order Edit API Routes](https://docs.medusajs.com/api/admin#order-edits).
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* An admin can edit an order to remove, add, or update an item's quantity. When an admin edits an order, they're stored as an `OrderEdit`.
*
* Related Guide: [How to edit an order](https://docs.medusajs.com/modules/orders/admin/edit-order).
*
* @customNamespace Hooks.Admin.Order Edits
*/
export * from "./queries"
export * from "./mutations"
@@ -20,6 +20,34 @@ import { buildOptions } from "../../utils/buildOptions"
import { adminOrderKeys } from "../orders"
import { adminOrderEditsKeys } from "./queries"
/**
* This hook creates an order edit.
*
* @example
* import React from "react"
* import { useAdminCreateOrderEdit } from "medusa-react"
*
* const CreateOrderEdit = () => {
* const createOrderEdit = useAdminCreateOrderEdit()
*
* const handleCreateOrderEdit = (orderId: string) => {
* createOrderEdit.mutate({
* order_id: orderId,
* }, {
* onSuccess: ({ order_edit }) => {
* console.log(order_edit.id)
* }
* })
* }
*
* // ...
* }
*
* export default CreateOrderEdit
*
* @customNamespace Hooks.Admin.Order Edits
* @category Mutations
*/
export const useAdminCreateOrderEdit = (
options?: UseMutationOptions<
Response<AdminOrderEditsRes>,
@@ -40,7 +68,42 @@ export const useAdminCreateOrderEdit = (
)
}
/**
* This hook deletes an order edit. Only order edits that have the status `created` can be deleted.
*
* @example
* import React from "react"
* import { useAdminDeleteOrderEdit } from "medusa-react"
*
* type Props = {
* orderEditId: string
* }
*
* const OrderEdit = ({ orderEditId }: Props) => {
* const deleteOrderEdit = useAdminDeleteOrderEdit(
* orderEditId
* )
*
* const handleDelete = () => {
* deleteOrderEdit.mutate(void 0, {
* onSuccess: ({ id, object, deleted }) => {
* console.log(id)
* }
* })
* }
*
* // ...
* }
*
* export default OrderEdit
*
* @customNamespace Hooks.Admin.Order Edits
* @category Mutations
*/
export const useAdminDeleteOrderEdit = (
/**
* Order Edit's ID
*/
id: string,
options?: UseMutationOptions<Response<AdminOrderEditDeleteRes>, Error, void>
) => {
@@ -61,8 +124,51 @@ export const useAdminDeleteOrderEdit = (
)
}
/**
* This hook deletes a line item change that indicates the addition, deletion, or update of a line item in the original order.
*
* @example
* import React from "react"
* import { useAdminDeleteOrderEditItemChange } from "medusa-react"
*
* type Props = {
* orderEditId: string
* itemChangeId: string
* }
*
* const OrderEditItemChange = ({
* orderEditId,
* itemChangeId
* }: Props) => {
* const deleteItemChange = useAdminDeleteOrderEditItemChange(
* orderEditId,
* itemChangeId
* )
*
* const handleDeleteItemChange = () => {
* deleteItemChange.mutate(void 0, {
* onSuccess: ({ id, object, deleted }) => {
* console.log(id)
* }
* })
* }
*
* // ...
* }
*
* export default OrderEditItemChange
*
* @customNamespace Hooks.Admin.Order Edits
* @category Mutations
*/
export const useAdminDeleteOrderEditItemChange = (
/**
* The order edit's ID.
*/
orderEditId: string,
/**
* The line item change's ID.
*/
itemChangeId: string,
options?: UseMutationOptions<
Response<AdminOrderEditItemChangeDeleteRes>,
@@ -83,8 +189,54 @@ export const useAdminDeleteOrderEditItemChange = (
)
}
/**
* This hook creates or updates a line item change in the order edit that indicates addition, deletion, or update of a line item
* into an original order. Line item changes are only reflected on the original order after the order edit is confirmed.
*
* @example
* import React from "react"
* import { useAdminOrderEditUpdateLineItem } from "medusa-react"
*
* type Props = {
* orderEditId: string
* itemId: string
* }
*
* const OrderEditItemChange = ({
* orderEditId,
* itemId
* }: Props) => {
* const updateLineItem = useAdminOrderEditUpdateLineItem(
* orderEditId,
* itemId
* )
*
* const handleUpdateLineItem = (quantity: number) => {
* updateLineItem.mutate({
* quantity,
* }, {
* onSuccess: ({ order_edit }) => {
* console.log(order_edit.items)
* }
* })
* }
*
* // ...
* }
*
* export default OrderEditItemChange
*
* @customNamespace Hooks.Admin.Order Edits
* @category Mutations
*/
export const useAdminOrderEditUpdateLineItem = (
/**
* The order edit's ID.
*/
orderEditId: string,
/**
* The line item's ID.
*/
itemId: string,
options?: UseMutationOptions<
Response<AdminOrderEditsRes>,
@@ -106,8 +258,52 @@ export const useAdminOrderEditUpdateLineItem = (
)
}
/**
* This hook creates a line item change in the order edit that indicates deleting an item in the original order.
* The item in the original order will not be deleted until the order edit is confirmed.
*
* @example
* import React from "react"
* import { useAdminOrderEditDeleteLineItem } from "medusa-react"
*
* type Props = {
* orderEditId: string
* itemId: string
* }
*
* const OrderEditLineItem = ({
* orderEditId,
* itemId
* }: Props) => {
* const removeLineItem = useAdminOrderEditDeleteLineItem(
* orderEditId,
* itemId
* )
*
* const handleRemoveLineItem = () => {
* removeLineItem.mutate(void 0, {
* onSuccess: ({ order_edit }) => {
* console.log(order_edit.changes)
* }
* })
* }
*
* // ...
* }
*
* export default OrderEditLineItem
*
* @customNamespace Hooks.Admin.Order Edits
* @category Mutations
*/
export const useAdminOrderEditDeleteLineItem = (
/**
* The order edit's ID.
*/
orderEditId: string,
/**
* The line item's ID.
*/
itemId: string,
options?: UseMutationOptions<Response<AdminOrderEditsRes>, Error>
) => {
@@ -124,7 +320,46 @@ export const useAdminOrderEditDeleteLineItem = (
)
}
/**
* This hook updates an Order Edit's details.
*
* @example
* import React from "react"
* import { useAdminUpdateOrderEdit } from "medusa-react"
*
* type Props = {
* orderEditId: string
* }
*
* const OrderEdit = ({ orderEditId }: Props) => {
* const updateOrderEdit = useAdminUpdateOrderEdit(
* orderEditId,
* )
*
* const handleUpdate = (
* internalNote: string
* ) => {
* updateOrderEdit.mutate({
* internal_note: internalNote
* }, {
* onSuccess: ({ order_edit }) => {
* console.log(order_edit.internal_note)
* }
* })
* }
*
* // ...
* }
*
* export default OrderEdit
*
* @customNamespace Hooks.Admin.Order Edits
* @category Mutations
*/
export const useAdminUpdateOrderEdit = (
/**
* The order edit's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminOrderEditsRes>,
@@ -150,7 +385,47 @@ export const useAdminUpdateOrderEdit = (
)
}
/**
* This hook creates a line item change in the order edit that indicates adding an item in the original order.
* The item will not be added to the original order until the order edit is confirmed.
*
* @example
* import React from "react"
* import { useAdminOrderEditAddLineItem } from "medusa-react"
*
* type Props = {
* orderEditId: string
* }
*
* const OrderEdit = ({ orderEditId }: Props) => {
* const addLineItem = useAdminOrderEditAddLineItem(
* orderEditId
* )
*
* const handleAddLineItem =
* (quantity: number, variantId: string) => {
* addLineItem.mutate({
* quantity,
* variant_id: variantId,
* }, {
* onSuccess: ({ order_edit }) => {
* console.log(order_edit.changes)
* }
* })
* }
*
* // ...
* }
*
* export default OrderEdit
*
* @customNamespace Hooks.Admin.Order Edits
* @category Mutations
*/
export const useAdminOrderEditAddLineItem = (
/**
* The order edit's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminOrderEditsRes>,
@@ -171,7 +446,49 @@ export const useAdminOrderEditAddLineItem = (
)
}
/**
* This hook requests customer confirmation of an order edit. This would emit the event `order-edit.requested` which Notification Providers listen to and send
* a notification to the customer about the order edit.
*
* @example
* import React from "react"
* import {
* useAdminRequestOrderEditConfirmation,
* } from "medusa-react"
*
* type Props = {
* orderEditId: string
* }
*
* const OrderEdit = ({ orderEditId }: Props) => {
* const requestOrderConfirmation =
* useAdminRequestOrderEditConfirmation(
* orderEditId
* )
*
* const handleRequestConfirmation = () => {
* requestOrderConfirmation.mutate(void 0, {
* onSuccess: ({ order_edit }) => {
* console.log(
* order_edit.requested_at,
* order_edit.requested_by
* )
* }
* })
* }
*
* // ...
* }
*
* export default OrderEdit
*
* @customNamespace Hooks.Admin.Order Edits
* @category Mutations
*/
export const useAdminRequestOrderEditConfirmation = (
/**
* The order edit's ID.
*/
id: string,
options?: UseMutationOptions<Response<AdminOrderEditsRes>, Error>
) => {
@@ -192,7 +509,47 @@ export const useAdminRequestOrderEditConfirmation = (
)
}
/**
* This hook cancels an order edit.
*
* @example
* import React from "react"
* import {
* useAdminCancelOrderEdit,
* } from "medusa-react"
*
* type Props = {
* orderEditId: string
* }
*
* const OrderEdit = ({ orderEditId }: Props) => {
* const cancelOrderEdit =
* useAdminCancelOrderEdit(
* orderEditId
* )
*
* const handleCancel = () => {
* cancelOrderEdit.mutate(void 0, {
* onSuccess: ({ order_edit }) => {
* console.log(
* order_edit.id
* )
* }
* })
* }
*
* // ...
* }
*
* export default OrderEdit
*
* @customNamespace Hooks.Admin.Order Edits
* @category Mutations
*/
export const useAdminCancelOrderEdit = (
/**
* The order edit's ID.
*/
id: string,
options?: UseMutationOptions<Response<AdminOrderEditsRes>, Error>
) => {
@@ -213,7 +570,45 @@ export const useAdminCancelOrderEdit = (
)
}
/**
* This hook confirms an order edit. This will reflect the changes in the order edit on the associated order.
*
* @example
* import React from "react"
* import { useAdminConfirmOrderEdit } from "medusa-react"
*
* type Props = {
* orderEditId: string
* }
*
* const OrderEdit = ({ orderEditId }: Props) => {
* const confirmOrderEdit = useAdminConfirmOrderEdit(
* orderEditId
* )
*
* const handleConfirmOrderEdit = () => {
* confirmOrderEdit.mutate(void 0, {
* onSuccess: ({ order_edit }) => {
* console.log(
* order_edit.confirmed_at,
* order_edit.confirmed_by
* )
* }
* })
* }
*
* // ...
* }
*
* export default OrderEdit
*
* @customNamespace Hooks.Admin.Order Edits
* @category Mutations
*/
export const useAdminConfirmOrderEdit = (
/**
* The order edit's ID.
*/
id: string,
options?: UseMutationOptions<Response<AdminOrderEditsRes>, Error>
) => {
@@ -15,8 +15,80 @@ const ADMIN_ORDER_EDITS_QUERY_KEY = `admin_order_edits` as const
export const adminOrderEditsKeys = queryKeysFactory(ADMIN_ORDER_EDITS_QUERY_KEY)
type OrderEditQueryKeys = typeof adminOrderEditsKeys
/**
* This hook retrieves an order edit's details.
*
* @example
* A simple example that retrieves an order edit by its ID:
*
* ```tsx
* import React from "react"
* import { useAdminOrderEdit } from "medusa-react"
*
* type Props = {
* orderEditId: string
* }
*
* const OrderEdit = ({ orderEditId }: Props) => {
* const {
* order_edit,
* isLoading,
* } = useAdminOrderEdit(orderEditId)
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {order_edit && <span>{order_edit.status}</span>}
* </div>
* )
* }
*
* export default OrderEdit
* ```
*
* To specify relations that should be retrieved:
*
* ```tsx
* import React from "react"
* import { useAdminOrderEdit } from "medusa-react"
*
* type Props = {
* orderEditId: string
* }
*
* const OrderEdit = ({ orderEditId }: Props) => {
* const {
* order_edit,
* isLoading,
* } = useAdminOrderEdit(
* orderEditId,
* {
* expand: "order"
* }
* )
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {order_edit && <span>{order_edit.status}</span>}
* </div>
* )
* }
*
* export default OrderEdit
* ```
*
* @customNamespace Hooks.Admin.Order Edits
* @category Queries
*/
export const useAdminOrderEdit = (
/**
* The order edit's ID.
*/
id: string,
/**
* Configurations to apply on the retrieved order edit.
*/
query?: GetOrderEditsOrderEditParams,
options?: UseQueryOptionsWrapper<
Response<AdminOrderEditsRes>,
@@ -33,7 +105,122 @@ export const useAdminOrderEdit = (
return { ...data, ...rest } as const
}
/**
* This hook retrieves a list of order edits. The order edits can be filtered by fields such as `q` or `order_id` passed to the `query` parameter.
* The order edits can also be paginated.
*
* @example
* To list order edits:
*
* ```tsx
* import React from "react"
* import { useAdminOrderEdits } from "medusa-react"
*
* const OrderEdits = () => {
* const { order_edits, isLoading } = useAdminOrderEdits()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {order_edits && !order_edits.length && (
* <span>No Order Edits</span>
* )}
* {order_edits && order_edits.length > 0 && (
* <ul>
* {order_edits.map((orderEdit) => (
* <li key={orderEdit.id}>
* {orderEdit.status}
* </li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default OrderEdits
* ```
*
* To specify relations that should be retrieved within the order edits:
*
* ```tsx
* import React from "react"
* import { useAdminOrderEdits } from "medusa-react"
*
* const OrderEdits = () => {
* const { order_edits, isLoading } = useAdminOrderEdits({
* expand: "order"
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {order_edits && !order_edits.length && (
* <span>No Order Edits</span>
* )}
* {order_edits && order_edits.length > 0 && (
* <ul>
* {order_edits.map((orderEdit) => (
* <li key={orderEdit.id}>
* {orderEdit.status}
* </li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default OrderEdits
* ```
*
* By default, only the first `50` records are retrieved. You can control pagination by specifying the `limit` and `offset` properties:
*
* ```tsx
* import React from "react"
* import { useAdminOrderEdits } from "medusa-react"
*
* const OrderEdits = () => {
* const {
* order_edits,
* limit,
* offset,
* isLoading
* } = useAdminOrderEdits({
* expand: "order",
* limit: 20,
* offset: 0
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {order_edits && !order_edits.length && (
* <span>No Order Edits</span>
* )}
* {order_edits && order_edits.length > 0 && (
* <ul>
* {order_edits.map((orderEdit) => (
* <li key={orderEdit.id}>
* {orderEdit.status}
* </li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default OrderEdits
* ```
*
* @customNamespace Hooks.Admin.Order Edits
* @category Queries
*/
export const useAdminOrderEdits = (
/**
* Filters and pagination configurations applied to retrieved order edits.
*/
query?: GetOrderEditsParams,
options?: UseQueryOptionsWrapper<
Response<AdminOrderEditsListRes>,
@@ -1,2 +1,16 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Order API Routes](https://docs.medusajs.com/api/admin#orders).
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* Orders are purchases made by customers, typically through a storefront using cart. Managing orders include managing fulfillment, payment, claims, reservations, and more.
*
* Related Guide: [How to manage orders](https://docs.medusajs.com/modules/orders/admin/manage-orders).
*
* @customNamespace Hooks.Admin.Orders
*/
export * from "./queries"
export * from "./mutations"
@@ -19,7 +19,46 @@ import { adminProductKeys } from "../products"
import { adminVariantKeys } from "../variants"
import { adminOrderKeys } from "./queries"
/**
* This hook updates an order's details.
*
* @example
* import React from "react"
* import { useAdminUpdateOrder } from "medusa-react"
*
* type Props = {
* orderId: string
* }
*
* const Order = ({ orderId }: Props) => {
* const updateOrder = useAdminUpdateOrder(
* orderId
* )
*
* const handleUpdate = (
* email: string
* ) => {
* updateOrder.mutate({
* email,
* }, {
* onSuccess: ({ order }) => {
* console.log(order.email)
* }
* })
* }
*
* // ...
* }
*
* export default Order
*
* @customNamespace Hooks.Admin.Orders
* @category Mutations
*/
export const useAdminUpdateOrder = (
/**
* The order's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminOrdersRes>,
@@ -41,7 +80,44 @@ export const useAdminUpdateOrder = (
)
}
/**
* This hook cancels an order and change its status. This will also cancel any associated fulfillments and payments,
* and it may fail if the payment or fulfillment Provider is unable to cancel the payment/fulfillment.
*
* @example
* import React from "react"
* import { useAdminCancelOrder } from "medusa-react"
*
* type Props = {
* orderId: string
* }
*
* const Order = ({ orderId }: Props) => {
* const cancelOrder = useAdminCancelOrder(
* orderId
* )
* // ...
*
* const handleCancel = () => {
* cancelOrder.mutate(void 0, {
* onSuccess: ({ order }) => {
* console.log(order.status)
* }
* })
* }
*
* // ...
* }
*
* export default Order
*
* @customNamespace Hooks.Admin.Orders
* @category Mutations
*/
export const useAdminCancelOrder = (
/**
* The order's ID.
*/
id: string,
options?: UseMutationOptions<Response<AdminOrdersRes>, Error, void>
) => {
@@ -58,7 +134,43 @@ export const useAdminCancelOrder = (
)
}
/**
* This hook completes an order and change its status. A canceled order can't be completed.
*
* @example
* import React from "react"
* import { useAdminCompleteOrder } from "medusa-react"
*
* type Props = {
* orderId: string
* }
*
* const Order = ({ orderId }: Props) => {
* const completeOrder = useAdminCompleteOrder(
* orderId
* )
* // ...
*
* const handleComplete = () => {
* completeOrder.mutate(void 0, {
* onSuccess: ({ order }) => {
* console.log(order.status)
* }
* })
* }
*
* // ...
* }
*
* export default Order
*
* @customNamespace Hooks.Admin.Orders
* @category Mutations
*/
export const useAdminCompleteOrder = (
/**
* The order's ID.
*/
id: string,
options?: UseMutationOptions<Response<AdminOrdersRes>, Error, void>
) => {
@@ -75,7 +187,43 @@ export const useAdminCompleteOrder = (
)
}
/**
* This hook captures all the payments associated with an order. The payment of canceled orders can't be captured.
*
* @example
* import React from "react"
* import { useAdminCapturePayment } from "medusa-react"
*
* type Props = {
* orderId: string
* }
*
* const Order = ({ orderId }: Props) => {
* const capturePayment = useAdminCapturePayment(
* orderId
* )
* // ...
*
* const handleCapture = () => {
* capturePayment.mutate(void 0, {
* onSuccess: ({ order }) => {
* console.log(order.status)
* }
* })
* }
*
* // ...
* }
*
* export default Order
*
* @customNamespace Hooks.Admin.Orders
* @category Mutations
*/
export const useAdminCapturePayment = (
/**
* The order's ID.
*/
id: string,
options?: UseMutationOptions<Response<AdminOrdersRes>, Error, void>
) => {
@@ -92,7 +240,49 @@ export const useAdminCapturePayment = (
)
}
/**
* This hook refunds an amount for an order. The amount must be less than or equal the `refundable_amount` of the order.
*
* @example
* import React from "react"
* import { useAdminRefundPayment } from "medusa-react"
*
* type Props = {
* orderId: string
* }
*
* const Order = ({ orderId }: Props) => {
* const refundPayment = useAdminRefundPayment(
* orderId
* )
* // ...
*
* const handleRefund = (
* amount: number,
* reason: string
* ) => {
* refundPayment.mutate({
* amount,
* reason,
* }, {
* onSuccess: ({ order }) => {
* console.log(order.refunds)
* }
* })
* }
*
* // ...
* }
*
* export default Order
*
* @customNamespace Hooks.Admin.Orders
* @category Mutations
*/
export const useAdminRefundPayment = (
/**
* The order's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminOrdersRes>,
@@ -114,7 +304,55 @@ export const useAdminRefundPayment = (
)
}
/**
* This hook creates a Fulfillment of an Order using the fulfillment provider, and change the order's
* fulfillment status to either `partially_fulfilled` or `fulfilled`, depending on
* whether all the items were fulfilled.
*
* @example
* import React from "react"
* import { useAdminCreateFulfillment } from "medusa-react"
*
* type Props = {
* orderId: string
* }
*
* const Order = ({ orderId }: Props) => {
* const createFulfillment = useAdminCreateFulfillment(
* orderId
* )
* // ...
*
* const handleCreateFulfillment = (
* itemId: string,
* quantity: number
* ) => {
* createFulfillment.mutate({
* items: [
* {
* item_id: itemId,
* quantity,
* },
* ],
* }, {
* onSuccess: ({ order }) => {
* console.log(order.fulfillments)
* }
* })
* }
*
* // ...
* }
*
* export default Order
*
* @customNamespace Hooks.Admin.Orders
* @category Mutations
*/
export const useAdminCreateFulfillment = (
/**
* The order's ID.
*/
orderId: string,
options?: UseMutationOptions<
Response<AdminOrdersRes>,
@@ -141,7 +379,47 @@ export const useAdminCreateFulfillment = (
)
}
/**
* This hook cancels an order's fulfillment and change its fulfillment status to `canceled`.
*
* @typeParamDefinition string - The fulfillment's ID.
*
* @example
* import React from "react"
* import { useAdminCancelFulfillment } from "medusa-react"
*
* type Props = {
* orderId: string
* }
*
* const Order = ({ orderId }: Props) => {
* const cancelFulfillment = useAdminCancelFulfillment(
* orderId
* )
* // ...
*
* const handleCancel = (
* fulfillmentId: string
* ) => {
* cancelFulfillment.mutate(fulfillmentId, {
* onSuccess: ({ order }) => {
* console.log(order.fulfillments)
* }
* })
* }
*
* // ...
* }
*
* export default Order
*
* @customNamespace Hooks.Admin.Orders
* @category Mutations
*/
export const useAdminCancelFulfillment = (
/**
* The order's ID.
*/
orderId: string,
options?: UseMutationOptions<Response<AdminOrdersRes>, Error, string>
) => {
@@ -159,7 +437,48 @@ export const useAdminCancelFulfillment = (
)
}
/**
* This hook creates a shipment and mark a fulfillment as shipped. This changes the order's fulfillment status to either
* `partially_shipped` or `shipped`, depending on whether all the items were shipped.
*
* @example
* import React from "react"
* import { useAdminCreateShipment } from "medusa-react"
*
* type Props = {
* orderId: string
* }
*
* const Order = ({ orderId }: Props) => {
* const createShipment = useAdminCreateShipment(
* orderId
* )
* // ...
*
* const handleCreate = (
* fulfillmentId: string
* ) => {
* createShipment.mutate({
* fulfillment_id: fulfillmentId,
* }, {
* onSuccess: ({ order }) => {
* console.log(order.fulfillment_status)
* }
* })
* }
*
* // ...
* }
*
* export default Order
*
* @customNamespace Hooks.Admin.Orders
* @category Mutations
*/
export const useAdminCreateShipment = (
/**
* The order's ID.
*/
orderId: string,
options?: UseMutationOptions<
Response<AdminOrdersRes>,
@@ -177,7 +496,53 @@ export const useAdminCreateShipment = (
)
}
/**
* This hook requests and create a return for items in an order. If the return shipping method is specified, it will be automatically fulfilled.
*
* @example
* import React from "react"
* import { useAdminRequestReturn } from "medusa-react"
*
* type Props = {
* orderId: string
* }
*
* const Order = ({ orderId }: Props) => {
* const requestReturn = useAdminRequestReturn(
* orderId
* )
* // ...
*
* const handleRequestingReturn = (
* itemId: string,
* quantity: number
* ) => {
* requestReturn.mutate({
* items: [
* {
* item_id: itemId,
* quantity
* }
* ]
* }, {
* onSuccess: ({ order }) => {
* console.log(order.returns)
* }
* })
* }
*
* // ...
* }
*
* export default Order
*
* @customNamespace Hooks.Admin.Orders
* @category Mutations
*/
export const useAdminRequestReturn = (
/**
* The order's ID.
*/
orderId: string,
options?: UseMutationOptions<
Response<AdminOrdersRes>,
@@ -195,7 +560,49 @@ export const useAdminRequestReturn = (
)
}
/**
* This hook adds a shipping method to an order. If another shipping method exists with the same shipping profile, the previous shipping method will be replaced.
*
* @example
* import React from "react"
* import { useAdminAddShippingMethod } from "medusa-react"
*
* type Props = {
* orderId: string
* }
*
* const Order = ({ orderId }: Props) => {
* const addShippingMethod = useAdminAddShippingMethod(
* orderId
* )
* // ...
*
* const handleAddShippingMethod = (
* optionId: string,
* price: number
* ) => {
* addShippingMethod.mutate({
* option_id: optionId,
* price
* }, {
* onSuccess: ({ order }) => {
* console.log(order.shipping_methods)
* }
* })
* }
*
* // ...
* }
*
* export default Order
*
* @customNamespace Hooks.Admin.Orders
* @category Mutations
*/
export const useAdminAddShippingMethod = (
/**
* The order's ID.
*/
orderId: string,
options?: UseMutationOptions<
Response<AdminOrdersRes>,
@@ -213,7 +620,43 @@ export const useAdminAddShippingMethod = (
)
}
/**
* The hook archives an order and change its status.
*
* @example
* import React from "react"
* import { useAdminArchiveOrder } from "medusa-react"
*
* type Props = {
* orderId: string
* }
*
* const Order = ({ orderId }: Props) => {
* const archiveOrder = useAdminArchiveOrder(
* orderId
* )
* // ...
*
* const handleArchivingOrder = () => {
* archiveOrder.mutate(void 0, {
* onSuccess: ({ order }) => {
* console.log(order.status)
* }
* })
* }
*
* // ...
* }
*
* export default Order
*
* @customNamespace Hooks.Admin.Orders
* @category Mutations
*/
export const useAdminArchiveOrder = (
/**
* The order's ID.
*/
id: string,
options?: UseMutationOptions<Response<AdminOrdersRes>, Error, void>
) => {
@@ -21,7 +21,82 @@ export const adminOrderKeys = {
type OrderQueryKeys = typeof adminOrderKeys
/**
* This hook retrieves a list of orders. The orders can be filtered by fields such as `status` or `display_id` passed
* in the `query` parameter. The order can also be paginated.
*
* @example
* To list orders:
*
* ```tsx
* import React from "react"
* import { useAdminOrders } from "medusa-react"
*
* const Orders = () => {
* const { orders, isLoading } = useAdminOrders()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {orders && !orders.length && <span>No Orders</span>}
* {orders && orders.length > 0 && (
* <ul>
* {orders.map((order) => (
* <li key={order.id}>{order.display_id}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default Orders
* ```
*
* You can use the `query` parameter to pass filters and specify relations that should be retrieved within the orders. In addition,
* By default, only the first `50` records are retrieved. You can control pagination by specifying the `limit` and `offset` properties:
*
* ```tsx
* import React from "react"
* import { useAdminOrders } from "medusa-react"
*
* const Orders = () => {
* const {
* orders,
* limit,
* offset,
* isLoading
* } = useAdminOrders({
* expand: "customers",
* limit: 20,
* offset: 0
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {orders && !orders.length && <span>No Orders</span>}
* {orders && orders.length > 0 && (
* <ul>
* {orders.map((order) => (
* <li key={order.id}>{order.display_id}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default Orders
* ```
*
* @customNamespace Hooks.Admin.Orders
* @category Queries
*/
export const useAdminOrders = (
/**
* Filters and pagination configurations applied on the retrieved orders.
*/
query?: AdminGetOrdersParams,
options?: UseQueryOptionsWrapper<
Response<AdminOrdersListRes>,
@@ -38,8 +113,77 @@ export const useAdminOrders = (
return { ...data, ...rest } as const
}
/**
* This hook retrieve an order's details.
*
* @example
* A simple example that retrieves an order by its ID:
*
* ```tsx
* import React from "react"
* import { useAdminOrder } from "medusa-react"
*
* type Props = {
* orderId: string
* }
*
* const Order = ({ orderId }: Props) => {
* const {
* order,
* isLoading,
* } = useAdminOrder(orderId)
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {order && <span>{order.display_id}</span>}
*
* </div>
* )
* }
*
* export default Order
* ```
*
* To specify relations that should be retrieved:
*
* ```tsx
* import React from "react"
* import { useAdminOrder } from "medusa-react"
*
* const Order = (
* orderId: string
* ) => {
* const {
* order,
* isLoading,
* } = useAdminOrder(orderId, {
* expand: "customer"
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {order && <span>{order.display_id}</span>}
*
* </div>
* )
* }
*
* export default Order
* ```
*
* @customNamespace Hooks.Admin.Orders
* @category Queries
*/
export const useAdminOrder = (
/**
* The order's ID.
*/
id: string,
/**
* Configurations to apply on the retrieved order.
*/
query?: FindParams,
options?: UseQueryOptionsWrapper<
Response<AdminOrdersRes>,
@@ -1,2 +1,14 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Payment Collection API Routes](https://docs.medusajs.com/api/admin#payment-collections).
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* A payment collection is useful for managing additional payments, such as for Order Edits, or installment payments.
*
* @customNamespace Hooks.Admin.Payment Collections
*/
export * from "./queries"
export * from "./mutations"
@@ -15,7 +15,43 @@ import { useMedusa } from "../../../contexts"
import { buildOptions } from "../../utils/buildOptions"
import { adminPaymentCollectionQueryKeys } from "./queries"
/**
* This hook deletes a payment collection. Only payment collections with the statuses `canceled` or `not_paid` can be deleted.
*
* @example
* import React from "react"
* import { useAdminDeletePaymentCollection } from "medusa-react"
*
* type Props = {
* paymentCollectionId: string
* }
*
* const PaymentCollection = ({ paymentCollectionId }: Props) => {
* const deleteCollection = useAdminDeletePaymentCollection(
* paymentCollectionId
* )
* // ...
*
* const handleDelete = () => {
* deleteCollection.mutate(void 0, {
* onSuccess: ({ id, object, deleted }) => {
* console.log(id)
* }
* })
* }
*
* // ...
* }
*
* export default PaymentCollection
*
* @customNamespace Hooks.Admin.Payment Collections
* @category Mutations
*/
export const useAdminDeletePaymentCollection = (
/**
* The payment collection's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminPaymentCollectionDeleteRes>,
@@ -39,7 +75,47 @@ export const useAdminDeletePaymentCollection = (
)
}
/**
* This hook updates a payment collection's details.
*
* @example
* import React from "react"
* import { useAdminUpdatePaymentCollection } from "medusa-react"
*
* type Props = {
* paymentCollectionId: string
* }
*
* const PaymentCollection = ({ paymentCollectionId }: Props) => {
* const updateCollection = useAdminUpdatePaymentCollection(
* paymentCollectionId
* )
* // ...
*
* const handleUpdate = (
* description: string
* ) => {
* updateCollection.mutate({
* description
* }, {
* onSuccess: ({ payment_collection }) => {
* console.log(payment_collection.description)
* }
* })
* }
*
* // ...
* }
*
* export default PaymentCollection
*
* @customNamespace Hooks.Admin.Payment Collections
* @category Mutations
*/
export const useAdminUpdatePaymentCollection = (
/**
* The payment collection's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminPaymentCollectionsRes>,
@@ -64,7 +140,43 @@ export const useAdminUpdatePaymentCollection = (
)
}
/**
* This hook sets the status of a payment collection as `authorized`. This will also change the `authorized_amount` of the payment collection.
*
* @example
* import React from "react"
* import { useAdminMarkPaymentCollectionAsAuthorized } from "medusa-react"
*
* type Props = {
* paymentCollectionId: string
* }
*
* const PaymentCollection = ({ paymentCollectionId }: Props) => {
* const markAsAuthorized = useAdminMarkPaymentCollectionAsAuthorized(
* paymentCollectionId
* )
* // ...
*
* const handleAuthorization = () => {
* markAsAuthorized.mutate(void 0, {
* onSuccess: ({ payment_collection }) => {
* console.log(payment_collection.status)
* }
* })
* }
*
* // ...
* }
*
* export default PaymentCollection
*
* @customNamespace Hooks.Admin.Payment Collections
* @category Mutations
*/
export const useAdminMarkPaymentCollectionAsAuthorized = (
/**
* The payment collection's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminPaymentCollectionsRes>,
@@ -13,7 +13,43 @@ export const adminPaymentCollectionQueryKeys = queryKeysFactory<
type AdminPaymentCollectionKey = typeof adminPaymentCollectionQueryKeys
/**
* This hook retrieves a Payment Collection's details.
*
* @example
* import React from "react"
* import { useAdminPaymentCollection } from "medusa-react"
*
* type Props = {
* paymentCollectionId: string
* }
*
* const PaymentCollection = ({ paymentCollectionId }: Props) => {
* const {
* payment_collection,
* isLoading,
* } = useAdminPaymentCollection(paymentCollectionId)
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {payment_collection && (
* <span>{payment_collection.status}</span>
* )}
*
* </div>
* )
* }
*
* export default PaymentCollection
*
* @customNamespace Hooks.Admin.Payment Collections
* @category Queries
*/
export const useAdminPaymentCollection = (
/**
* The payment collection's ID.
*/
id: string,
options?: UseQueryOptionsWrapper<
Response<AdminPaymentCollectionsRes>,
@@ -1,2 +1,14 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Payment API Routes](https://docs.medusajs.com/api/admin#payments).
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* A payment can be related to an order, swap, return, or more. It can be captured or refunded.
*
* @customNamespace Hooks.Admin.Payments
*/
export * from "./queries"
export * from "./mutations"
@@ -15,7 +15,43 @@ import { useMedusa } from "../../../contexts"
import { buildOptions } from "../../utils/buildOptions"
import { adminPaymentQueryKeys } from "./queries"
/**
* This hook captures a payment.
*
* @example
* import React from "react"
* import { useAdminPaymentsCapturePayment } from "medusa-react"
*
* type Props = {
* paymentId: string
* }
*
* const Payment = ({ paymentId }: Props) => {
* const capture = useAdminPaymentsCapturePayment(
* paymentId
* )
* // ...
*
* const handleCapture = () => {
* capture.mutate(void 0, {
* onSuccess: ({ payment }) => {
* console.log(payment.amount)
* }
* })
* }
*
* // ...
* }
*
* export default Payment
*
* @customNamespace Hooks.Admin.Payments
* @category Mutations
*/
export const useAdminPaymentsCapturePayment = (
/**
* The payment's ID.
*/
id: string,
options?: UseMutationOptions<Response<AdminPaymentRes>, Error, void>
) => {
@@ -32,7 +68,52 @@ export const useAdminPaymentsCapturePayment = (
)
}
/**
* This hook refunds a payment. The payment must be captured first.
*
* @example
* import React from "react"
* import { RefundReason } from "@medusajs/medusa"
* import { useAdminPaymentsRefundPayment } from "medusa-react"
*
* type Props = {
* paymentId: string
* }
*
* const Payment = ({ paymentId }: Props) => {
* const refund = useAdminPaymentsRefundPayment(
* paymentId
* )
* // ...
*
* const handleRefund = (
* amount: number,
* reason: RefundReason,
* note: string
* ) => {
* refund.mutate({
* amount,
* reason,
* note
* }, {
* onSuccess: ({ refund }) => {
* console.log(refund.amount)
* }
* })
* }
*
* // ...
* }
*
* export default Payment
*
* @customNamespace Hooks.Admin.Payments
* @category Mutations
*/
export const useAdminPaymentsRefundPayment = (
/**
* The payment's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminRefundRes>,
@@ -12,7 +12,41 @@ export const adminPaymentQueryKeys =
type AdminPaymentKey = typeof adminPaymentQueryKeys
/**
* This hook retrieves a payment's details.
*
* @example
* import React from "react"
* import { useAdminPayment } from "medusa-react"
*
* type Props = {
* paymentId: string
* }
*
* const Payment = ({ paymentId }: Props) => {
* const {
* payment,
* isLoading,
* } = useAdminPayment(paymentId)
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {payment && <span>{payment.amount}</span>}
*
* </div>
* )
* }
*
* export default Payment
*
* @customNamespace Hooks.Admin.Payments
* @category Queries
*/
export const useAdminPayment = (
/**
* The payment's ID.
*/
id: string,
options?: UseQueryOptionsWrapper<
Response<AdminPaymentRes>,
@@ -1,2 +1,16 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Price List API Routes](https://docs.medusajs.com/api/admin#price-lists).
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* A price list are special prices applied to products based on a set of conditions, such as customer group.
*
* Related Guide: [How to manage price lists](https://docs.medusajs.com/modules/price-lists/admin/manage-price-lists).
*
* @customNamespace Hooks.Admin.Price Lists
*/
export * from "./queries"
export * from "./mutations"
@@ -22,6 +22,52 @@ import { adminProductKeys } from "../products"
import { adminVariantKeys } from "../variants"
import { adminPriceListKeys } from "./queries"
/**
* This hook creates a price list.
*
* @example
* import React from "react"
* import {
* PriceListStatus,
* PriceListType,
* } from "@medusajs/medusa"
* import { useAdminCreatePriceList } from "medusa-react"
*
* type CreateData = {
* name: string
* description: string
* type: PriceListType
* status: PriceListStatus
* prices: {
* amount: number
* variant_id: string
* currency_code: string
* max_quantity: number
* }[]
* }
*
* const CreatePriceList = () => {
* const createPriceList = useAdminCreatePriceList()
* // ...
*
* const handleCreate = (
* data: CreateData
* ) => {
* createPriceList.mutate(data, {
* onSuccess: ({ price_list }) => {
* console.log(price_list.id)
* }
* })
* }
*
* // ...
* }
*
* export default CreatePriceList
*
* @customNamespace Hooks.Admin.Price Lists
* @category Mutations
*/
export const useAdminCreatePriceList = (
options?: UseMutationOptions<
Response<AdminPriceListRes>,
@@ -38,7 +84,47 @@ export const useAdminCreatePriceList = (
)
}
/**
* This hook updates a price list's details.
*
* @example
* import React from "react"
* import { useAdminUpdatePriceList } from "medusa-react"
*
* type Props = {
* priceListId: string
* }
*
* const PriceList = ({
* priceListId
* }: Props) => {
* const updatePriceList = useAdminUpdatePriceList(priceListId)
* // ...
*
* const handleUpdate = (
* endsAt: Date
* ) => {
* updatePriceList.mutate({
* ends_at: endsAt,
* }, {
* onSuccess: ({ price_list }) => {
* console.log(price_list.ends_at)
* }
* })
* }
*
* // ...
* }
*
* export default PriceList
*
* @customNamespace Hooks.Admin.Price Lists
* @category Mutations
*/
export const useAdminUpdatePriceList = (
/**
* The price list's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminPriceListRes>,
@@ -64,7 +150,43 @@ export const useAdminUpdatePriceList = (
)
}
/**
* This hook deletes a price list and its associated prices.
*
* @example
* import React from "react"
* import { useAdminDeletePriceList } from "medusa-react"
*
* type Props = {
* priceListId: string
* }
*
* const PriceList = ({
* priceListId
* }: Props) => {
* const deletePriceList = useAdminDeletePriceList(priceListId)
* // ...
*
* const handleDelete = () => {
* deletePriceList.mutate(void 0, {
* onSuccess: ({ id, object, deleted }) => {
* console.log(id)
* }
* })
* }
*
* // ...
* }
*
* export default PriceList
*
* @customNamespace Hooks.Admin.Price Lists
* @category Mutations
*/
export const useAdminDeletePriceList = (
/**
* The price list's ID.
*/
id: string,
options?: UseMutationOptions<Response<AdminPriceListDeleteRes>, Error, void>
) => {
@@ -81,7 +203,51 @@ export const useAdminDeletePriceList = (
)
}
/**
* This hook adds or updates a list of prices in a price list.
*
* @example
* import React from "react"
* import { useAdminCreatePriceListPrices } from "medusa-react"
*
* type PriceData = {
* amount: number
* variant_id: string
* currency_code: string
* }
*
* type Props = {
* priceListId: string
* }
*
* const PriceList = ({
* priceListId
* }: Props) => {
* const addPrices = useAdminCreatePriceListPrices(priceListId)
* // ...
*
* const handleAddPrices = (prices: PriceData[]) => {
* addPrices.mutate({
* prices
* }, {
* onSuccess: ({ price_list }) => {
* console.log(price_list.prices)
* }
* })
* }
*
* // ...
* }
*
* export default PriceList
*
* @customNamespace Hooks.Admin.Price Lists
* @category Mutations
*/
export const useAdminCreatePriceListPrices = (
/**
* The price list's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminPriceListRes>,
@@ -106,7 +272,45 @@ export const useAdminCreatePriceListPrices = (
)
}
/**
* This hook deletes a list of prices in a price list.
*
* @example
* import React from "react"
* import { useAdminDeletePriceListPrices } from "medusa-react"
*
* type Props = {
* priceListId: string
* }
*
* const PriceList = ({
* priceListId
* }: Props) => {
* const deletePrices = useAdminDeletePriceListPrices(priceListId)
* // ...
*
* const handleDeletePrices = (priceIds: string[]) => {
* deletePrices.mutate({
* price_ids: priceIds
* }, {
* onSuccess: ({ ids, deleted, object }) => {
* console.log(ids)
* }
* })
* }
*
* // ...
* }
*
* export default PriceList
*
* @customNamespace Hooks.Admin.Price Lists
* @category Mutations
*/
export const useAdminDeletePriceListPrices = (
/**
* The price list's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminPriceListDeleteBatchRes>,
@@ -132,7 +336,47 @@ export const useAdminDeletePriceListPrices = (
)
}
/**
* This hook deletes all the prices associated with multiple products in a price list.
*
* @example
* import React from "react"
* import { useAdminDeletePriceListProductsPrices } from "medusa-react"
*
* type Props = {
* priceListId: string
* }
*
* const PriceList = ({
* priceListId
* }: Props) => {
* const deleteProductsPrices = useAdminDeletePriceListProductsPrices(
* priceListId
* )
* // ...
*
* const handleDeleteProductsPrices = (productIds: string[]) => {
* deleteProductsPrices.mutate({
* product_ids: productIds
* }, {
* onSuccess: ({ ids, deleted, object }) => {
* console.log(ids)
* }
* })
* }
*
* // ...
* }
*
* export default PriceList
*
* @customNamespace Hooks.Admin.Price Lists
* @category Mutations
*/
export const useAdminDeletePriceListProductsPrices = (
/**
* The price list's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminPriceListDeleteBatchRes>,
@@ -154,8 +398,54 @@ export const useAdminDeletePriceListProductsPrices = (
)
}
/**
* This hook deletes all the prices related to a specific product in a price list.
*
* @example
* import React from "react"
* import {
* useAdminDeletePriceListProductPrices
* } from "medusa-react"
*
* type Props = {
* priceListId: string
* productId: string
* }
*
* const PriceListProduct = ({
* priceListId,
* productId
* }: Props) => {
* const deleteProductPrices = useAdminDeletePriceListProductPrices(
* priceListId,
* productId
* )
* // ...
*
* const handleDeleteProductPrices = () => {
* deleteProductPrices.mutate(void 0, {
* onSuccess: ({ ids, deleted, object }) => {
* console.log(ids)
* }
* })
* }
*
* // ...
* }
*
* export default PriceListProduct
*
* @customNamespace Hooks.Admin.Price Lists
* @category Mutations
*/
export const useAdminDeletePriceListProductPrices = (
/**
* The price list's ID.
*/
id: string,
/**
* The product's ID.
*/
productId: string,
options?: UseMutationOptions<
Response<AdminPriceListDeleteProductPricesRes>,
@@ -179,8 +469,54 @@ export const useAdminDeletePriceListProductPrices = (
)
}
/**
* This hook deletes all the prices related to a specific product variant in a price list.
*
* @example
* import React from "react"
* import {
* useAdminDeletePriceListVariantPrices
* } from "medusa-react"
*
* type Props = {
* priceListId: string
* variantId: string
* }
*
* const PriceListVariant = ({
* priceListId,
* variantId
* }: Props) => {
* const deleteVariantPrices = useAdminDeletePriceListVariantPrices(
* priceListId,
* variantId
* )
* // ...
*
* const handleDeleteVariantPrices = () => {
* deleteVariantPrices.mutate(void 0, {
* onSuccess: ({ ids, deleted, object }) => {
* console.log(ids)
* }
* })
* }
*
* // ...
* }
*
* export default PriceListVariant
*
* @customNamespace Hooks.Admin.Price Lists
* @category Mutations
*/
export const useAdminDeletePriceListVariantPrices = (
/**
* The price list's ID.
*/
id: string,
/**
* The product variant's ID.
*/
variantId: string,
options?: UseMutationOptions<
Response<AdminPriceListDeleteVariantPricesRes>,
@@ -26,7 +26,116 @@ export const adminPriceListKeys = {
type PriceListQueryKeys = typeof adminPriceListKeys
/**
* This hook retrieves a list of price lists. The price lists can be filtered by fields such as `q` or `status` passed
* in the `query` parameter. The price lists can also be sorted or paginated.
*
* @example
* To list price lists:
*
* ```tsx
* import React from "react"
* import { useAdminPriceLists } from "medusa-react"
*
* const PriceLists = () => {
* const { price_lists, isLoading } = useAdminPriceLists()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {price_lists && !price_lists.length && (
* <span>No Price Lists</span>
* )}
* {price_lists && price_lists.length > 0 && (
* <ul>
* {price_lists.map((price_list) => (
* <li key={price_list.id}>{price_list.name}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default PriceLists
* ```
*
* To specify relations that should be retrieved within the price lists:
*
* ```tsx
* import React from "react"
* import { useAdminPriceLists } from "medusa-react"
*
* const PriceLists = () => {
* const { price_lists, isLoading } = useAdminPriceLists({
* expand: "prices"
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {price_lists && !price_lists.length && (
* <span>No Price Lists</span>
* )}
* {price_lists && price_lists.length > 0 && (
* <ul>
* {price_lists.map((price_list) => (
* <li key={price_list.id}>{price_list.name}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default PriceLists
* ```
*
* By default, only the first `10` records are retrieved. You can control pagination by specifying the `limit` and `offset` properties:
*
* ```tsx
* import React from "react"
* import { useAdminPriceLists } from "medusa-react"
*
* const PriceLists = () => {
* const {
* price_lists,
* limit,
* offset,
* isLoading
* } = useAdminPriceLists({
* expand: "prices",
* limit: 20,
* offset: 0
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {price_lists && !price_lists.length && (
* <span>No Price Lists</span>
* )}
* {price_lists && price_lists.length > 0 && (
* <ul>
* {price_lists.map((price_list) => (
* <li key={price_list.id}>{price_list.name}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default PriceLists
* ```
*
* @customNamespace Hooks.Admin.Price Lists
* @category Queries
*/
export const useAdminPriceLists = (
/**
* Filters and pagination configurations to apply on the retrieved price lists.
*/
query?: AdminGetPriceListPaginationParams,
options?: UseQueryOptionsWrapper<
Response<AdminPriceListsListRes>,
@@ -43,8 +152,146 @@ export const useAdminPriceLists = (
return { ...data, ...rest } as const
}
/**
* This hook retrieves a price list's products. The products can be filtered by fields such as `q` or `status`
* passed in the `query` parameter. The products can also be sorted or paginated.
*
* @example
* To list products in a price list:
*
* ```tsx
* import React from "react"
* import { useAdminPriceListProducts } from "medusa-react"
*
* type Props = {
* priceListId: string
* }
*
* const PriceListProducts = ({
* priceListId
* }: Props) => {
* const { products, isLoading } = useAdminPriceListProducts(
* priceListId
* )
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {products && !products.length && (
* <span>No Price Lists</span>
* )}
* {products && products.length > 0 && (
* <ul>
* {products.map((product) => (
* <li key={product.id}>{product.title}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default PriceListProducts
* ```
*
* To specify relations that should be retrieved within the products:
*
* ```tsx
* import React from "react"
* import { useAdminPriceListProducts } from "medusa-react"
*
* type Props = {
* priceListId: string
* }
*
* const PriceListProducts = ({
* priceListId
* }: Props) => {
* const { products, isLoading } = useAdminPriceListProducts(
* priceListId,
* {
* expand: "variants"
* }
* )
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {products && !products.length && (
* <span>No Price Lists</span>
* )}
* {products && products.length > 0 && (
* <ul>
* {products.map((product) => (
* <li key={product.id}>{product.title}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default PriceListProducts
* ```
*
* By default, only the first `50` records are retrieved. You can control pagination by specifying the `limit` and `offset` properties:
*
* ```tsx
* import React from "react"
* import { useAdminPriceListProducts } from "medusa-react"
*
* type Props = {
* priceListId: string
* }
*
* const PriceListProducts = ({
* priceListId
* }: Props) => {
* const {
* products,
* limit,
* offset,
* isLoading
* } = useAdminPriceListProducts(
* priceListId,
* {
* expand: "variants",
* limit: 20,
* offset: 0
* }
* )
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {products && !products.length && (
* <span>No Price Lists</span>
* )}
* {products && products.length > 0 && (
* <ul>
* {products.map((product) => (
* <li key={product.id}>{product.title}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default PriceListProducts
* ```
*
* @customNamespace Hooks.Admin.Price Lists
* @category Queries
*/
export const useAdminPriceListProducts = (
/**
* The ID of the associated price list.
*/
id: string,
/**
* Filters and pagination configurations applied on the retrieved products.
*/
query?: AdminGetPriceListsPriceListProductsParams,
options?: UseQueryOptionsWrapper<
Response<AdminProductsListRes>,
@@ -61,7 +308,42 @@ export const useAdminPriceListProducts = (
return { ...data, ...rest } as const
}
/**
* This hook retrieves a price list's details.
*
* @example
* import React from "react"
* import { useAdminPriceList } from "medusa-react"
*
* type Props = {
* priceListId: string
* }
*
* const PriceList = ({
* priceListId
* }: Props) => {
* const {
* price_list,
* isLoading,
* } = useAdminPriceList(priceListId)
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {price_list && <span>{price_list.name}</span>}
* </div>
* )
* }
*
* export default PriceList
*
* @customNamespace Hooks.Admin.Price Lists
* @category Queries
*/
export const useAdminPriceList = (
/**
* The price list's ID.
*/
id: string,
options?: UseQueryOptionsWrapper<
Response<AdminPriceListRes>,
@@ -1,2 +1,18 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Product Category API Routes](https://docs.medusajs.com/api/admin#product-categories).
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* Products can be categoriezed into categories. A product can be added into more than one category.
*
* Related Guide: [How to manage product categories](https://docs.medusajs.com/modules/products/admin/manage-categories).
*
* @featureFlag product_categories
*
* @customNamespace Hooks.Admin.Product Categories
*/
export * from "./queries"
export * from "./mutations"
@@ -19,10 +19,35 @@ import { adminProductCategoryKeys } from "./queries"
import { adminProductKeys } from "../products"
/**
* Hook provides a mutation function for creating product categories.
*
* @experimental This feature is under development and may change in the future.
* To use this feature please enable the corresponding feature flag in your medusa backend project.
* This hook creates a product category.
*
* @example
* import React from "react"
* import { useAdminCreateProductCategory } from "medusa-react"
*
* const CreateCategory = () => {
* const createCategory = useAdminCreateProductCategory()
* // ...
*
* const handleCreate = (
* name: string
* ) => {
* createCategory.mutate({
* name,
* }, {
* onSuccess: ({ product_category }) => {
* console.log(product_category.id)
* }
* })
* }
*
* // ...
* }
*
* export default CreateCategory
*
* @customNamespace Hooks.Admin.Product Categories
* @category Mutations
*/
export const useAdminCreateProductCategory = (
options?: UseMutationOptions<
@@ -45,14 +70,49 @@ export const useAdminCreateProductCategory = (
)
}
/** Update a product category
*
* @experimental This feature is under development and may change in the future.
* To use this feature please enable feature flag `product_categories` in your medusa backend project.
* @description updates a product category
* @returns the updated medusa product category
/**
* This hook updates a product category.
*
* @example
* import React from "react"
* import { useAdminUpdateProductCategory } from "medusa-react"
*
* type Props = {
* productCategoryId: string
* }
*
* const Category = ({
* productCategoryId
* }: Props) => {
* const updateCategory = useAdminUpdateProductCategory(
* productCategoryId
* )
* // ...
*
* const handleUpdate = (
* name: string
* ) => {
* updateCategory.mutate({
* name,
* }, {
* onSuccess: ({ product_category }) => {
* console.log(product_category.id)
* }
* })
* }
*
* // ...
* }
*
* export default Category
*
* @customNamespace Hooks.Admin.Product Categories
* @category Mutations
*/
export const useAdminUpdateProductCategory = (
/**
* The product category's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminProductCategoriesCategoryRes>,
@@ -78,14 +138,44 @@ export const useAdminUpdateProductCategory = (
}
/**
* Delete a product category
*
* @experimental This feature is under development and may change in the future.
* To use this feature please enable featureflag `product_categories` in your medusa backend project.
* @param id
* @param options
* This hook deletes a product category. This does not delete associated products.
*
* @example
* import React from "react"
* import { useAdminDeleteProductCategory } from "medusa-react"
*
* type Props = {
* productCategoryId: string
* }
*
* const Category = ({
* productCategoryId
* }: Props) => {
* const deleteCategory = useAdminDeleteProductCategory(
* productCategoryId
* )
* // ...
*
* const handleDelete = () => {
* deleteCategory.mutate(void 0, {
* onSuccess: ({ id, object, deleted }) => {
* console.log(id)
* }
* })
* }
*
* // ...
* }
*
* export default Category
*
* @customNamespace Hooks.Admin.Product Categories
* @category Mutations
*/
export const useAdminDeleteProductCategory = (
/**
* The product category's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminProductCategoriesCategoryDeleteRes>,
@@ -111,15 +201,52 @@ export const useAdminDeleteProductCategory = (
}
/**
* Add products to a product category
*
* @experimental This feature is under development and may change in the future.
* To use this feature please enable featureflag `product_categories` in your medusa backend project.
* @description Add products to a product category
* @param id
* @param options
* This hook adds a list of products to a product category.
*
* @example
* import React from "react"
* import { useAdminAddProductsToCategory } from "medusa-react"
*
* type ProductsData = {
* id: string
* }
*
* type Props = {
* productCategoryId: string
* }
*
* const Category = ({
* productCategoryId
* }: Props) => {
* const addProducts = useAdminAddProductsToCategory(
* productCategoryId
* )
* // ...
*
* const handleAddProducts = (
* productIds: ProductsData[]
* ) => {
* addProducts.mutate({
* product_ids: productIds
* }, {
* onSuccess: ({ product_category }) => {
* console.log(product_category.products)
* }
* })
* }
*
* // ...
* }
*
* export default Category
*
* @customNamespace Hooks.Admin.Product Categories
* @category Mutations
*/
export const useAdminAddProductsToCategory = (
/**
* The product category's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminProductCategoriesCategoryRes>,
@@ -146,14 +273,52 @@ export const useAdminAddProductsToCategory = (
}
/**
* Remove products from a product category
* @experimental This feature is under development and may change in the future.
* To use this feature please enable featureflag `product_categories` in your medusa backend project.
* @description remove products from a product category
* @param id
* @param options
* This hook removes a list of products from a product category.
*
* @example
* import React from "react"
* import { useAdminDeleteProductsFromCategory } from "medusa-react"
*
* type ProductsData = {
* id: string
* }
*
* type Props = {
* productCategoryId: string
* }
*
* const Category = ({
* productCategoryId
* }: Props) => {
* const deleteProducts = useAdminDeleteProductsFromCategory(
* productCategoryId
* )
* // ...
*
* const handleDeleteProducts = (
* productIds: ProductsData[]
* ) => {
* deleteProducts.mutate({
* product_ids: productIds
* }, {
* onSuccess: ({ product_category }) => {
* console.log(product_category.products)
* }
* })
* }
*
* // ...
* }
*
* export default Category
*
* @customNamespace Hooks.Admin.Product Categories
* @category Mutations
*/
export const useAdminDeleteProductsFromCategory = (
/**
* The product category's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminProductCategoriesCategoryRes>,
@@ -17,7 +17,127 @@ export const adminProductCategoryKeys = queryKeysFactory(
)
type ProductCategoryQueryKeys = typeof adminProductCategoryKeys
/**
* This hook
*
* @example
* To list product categories:
*
* ```tsx
* import React from "react"
* import { useAdminProductCategories } from "medusa-react"
*
* function Categories() {
* const {
* product_categories,
* isLoading
* } = useAdminProductCategories()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {product_categories && !product_categories.length && (
* <span>No Categories</span>
* )}
* {product_categories && product_categories.length > 0 && (
* <ul>
* {product_categories.map(
* (category) => (
* <li key={category.id}>{category.name}</li>
* )
* )}
* </ul>
* )}
* </div>
* )
* }
*
* export default Categories
* ```
*
* To specify relations that should be retrieved within the product category:
*
* ```tsx
* import React from "react"
* import { useAdminProductCategories } from "medusa-react"
*
* function Categories() {
* const {
* product_categories,
* isLoading
* } = useAdminProductCategories({
* expand: "category_children"
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {product_categories && !product_categories.length && (
* <span>No Categories</span>
* )}
* {product_categories && product_categories.length > 0 && (
* <ul>
* {product_categories.map(
* (category) => (
* <li key={category.id}>{category.name}</li>
* )
* )}
* </ul>
* )}
* </div>
* )
* }
*
* export default Categories
* ```
*
* By default, only the first `100` records are retrieved. You can control pagination by specifying the `limit` and `offset` properties:
*
* ```tsx
* import React from "react"
* import { useAdminProductCategories } from "medusa-react"
*
* function Categories() {
* const {
* product_categories,
* limit,
* offset,
* isLoading
* } = useAdminProductCategories({
* expand: "category_children",
* limit: 20,
* offset: 0
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {product_categories && !product_categories.length && (
* <span>No Categories</span>
* )}
* {product_categories && product_categories.length > 0 && (
* <ul>
* {product_categories.map(
* (category) => (
* <li key={category.id}>{category.name}</li>
* )
* )}
* </ul>
* )}
* </div>
* )
* }
*
* export default Categories
* ```
*
* @customNamespace Hooks.Admin.Product Categories
* @category Queries
*/
export const useAdminProductCategories = (
/**
* Filters and pagination configurations to apply on the retrieved product categories.
*/
query?: AdminGetProductCategoriesParams,
options?: UseQueryOptionsWrapper<
Response<AdminProductCategoriesListRes>,
@@ -34,8 +154,87 @@ export const useAdminProductCategories = (
return { ...data, ...rest } as const
}
/**
* This hook retrieves a product category's details.
*
* @example
* A simple example that retrieves an order by its ID:
*
* ```tsx
* import React from "react"
* import { useAdminProductCategory } from "medusa-react"
*
* type Props = {
* productCategoryId: string
* }
*
* const Category = ({
* productCategoryId
* }: Props) => {
* const {
* product_category,
* isLoading,
* } = useAdminProductCategory(productCategoryId)
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {product_category && (
* <span>{product_category.name}</span>
* )}
*
* </div>
* )
* }
*
* export default Category
* ```
*
* To specify relations that should be retrieved:
*
* ```tsx
* import React from "react"
* import { useAdminProductCategory } from "medusa-react"
*
* type Props = {
* productCategoryId: string
* }
*
* const Category = ({
* productCategoryId
* }: Props) => {
* const {
* product_category,
* isLoading,
* } = useAdminProductCategory(productCategoryId, {
* expand: "category_children"
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {product_category && (
* <span>{product_category.name}</span>
* )}
*
* </div>
* )
* }
*
* export default Category
* ```
*
* @customNamespace Hooks.Admin.Product Categories
* @category Queries
*/
export const useAdminProductCategory = (
/**
* The product category's ID.
*/
id: string,
/**
* Configurations to apply on the retrieved product category.
*/
query?: AdminGetProductCategoryParams,
options?: UseQueryOptionsWrapper<
Response<AdminProductCategoriesCategoryRes>,
@@ -1 +1,14 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Product Tag API Routes](https://docs.medusajs.com/api/admin#product-tags).
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* Product tags are string values created when you create or update a product with a new tag.
* Products can have more than one tag, and products can share tags. This allows admins to associate products to similar tags that can be used to filter products.
*
* @customNamespace Hooks.Admin.Product Tags
*/
export * from "./queries"
@@ -16,7 +16,91 @@ export const adminProductTagKeys = queryKeysFactory(
type ProductQueryKeys = typeof adminProductTagKeys
/**
* This hook retrieves a list of product tags. The product tags can be filtered by fields such as `q` or `value` passed
* in the `query` parameter. The product tags can also be sorted or paginated.
*
* @example
* To list product tags:
*
* ```tsx
* import React from "react"
* import { useAdminProductTags } from "medusa-react"
*
* function ProductTags() {
* const {
* product_tags,
* isLoading
* } = useAdminProductTags()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {product_tags && !product_tags.length && (
* <span>No Product Tags</span>
* )}
* {product_tags && product_tags.length > 0 && (
* <ul>
* {product_tags.map(
* (tag) => (
* <li key={tag.id}>{tag.value}</li>
* )
* )}
* </ul>
* )}
* </div>
* )
* }
*
* export default ProductTags
* ```
*
* By default, only the first `10` records are retrieved. You can control pagination by specifying the `limit` and `offset` properties:
*
* ```tsx
* import React from "react"
* import { useAdminProductTags } from "medusa-react"
*
* function ProductTags() {
* const {
* product_tags,
* limit,
* offset,
* isLoading
* } = useAdminProductTags({
* limit: 20,
* offset: 0
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {product_tags && !product_tags.length && (
* <span>No Product Tags</span>
* )}
* {product_tags && product_tags.length > 0 && (
* <ul>
* {product_tags.map(
* (tag) => (
* <li key={tag.id}>{tag.value}</li>
* )
* )}
* </ul>
* )}
* </div>
* )
* }
*
* export default ProductTags
* ```
*
* @customNamespace Hooks.Admin.Product Tags
* @category Queries
*/
export const useAdminProductTags = (
/**
* Filters and pagination configurations to apply on the retrieved product tags.
*/
query?: AdminGetProductTagsParams,
options?: UseQueryOptionsWrapper<
Response<AdminProductTagsListRes>,
@@ -1 +1,14 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Product Type API Routes](https://docs.medusajs.com/api/admin#product-types).
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* Product types are string values created when you create or update a product with a new type.
* Products can have one type, and products can share types. This allows admins to associate products with a type that can be used to filter products.
*
* @customNamespace Hooks.Admin.Product Types
*/
export * from "./queries"
@@ -16,7 +16,91 @@ export const adminProductTypeKeys = queryKeysFactory(
type ProductTypesQueryKeys = typeof adminProductTypeKeys
/**
* This hook retrieves a list of product types. The product types can be filtered by fields such as `q` or `value` passed in the `query` parameter.
* The product types can also be sorted or paginated.
*
* @example
* To list product types:
*
* ```tsx
* import React from "react"
* import { useAdminProductTypes } from "medusa-react"
*
* function ProductTypes() {
* const {
* product_types,
* isLoading
* } = useAdminProductTypes()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {product_types && !product_types.length && (
* <span>No Product Tags</span>
* )}
* {product_types && product_types.length > 0 && (
* <ul>
* {product_types.map(
* (type) => (
* <li key={type.id}>{type.value}</li>
* )
* )}
* </ul>
* )}
* </div>
* )
* }
*
* export default ProductTypes
* ```
*
* By default, only the first `20` records are retrieved. You can control pagination by specifying the `limit` and `offset` properties:
*
* ```tsx
* import React from "react"
* import { useAdminProductTypes } from "medusa-react"
*
* function ProductTypes() {
* const {
* product_types,
* limit,
* offset,
* isLoading
* } = useAdminProductTypes({
* limit: 10,
* offset: 0
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {product_types && !product_types.length && (
* <span>No Product Tags</span>
* )}
* {product_types && product_types.length > 0 && (
* <ul>
* {product_types.map(
* (type) => (
* <li key={type.id}>{type.value}</li>
* )
* )}
* </ul>
* )}
* </div>
* )
* }
*
* export default ProductTypes
* ```
*
* @customNamespace Hooks.Admin.Product Types
* @category Queries
*/
export const useAdminProductTypes = (
/**
* Filters and pagination configurations to apply on the retrieved product types.
*/
query?: AdminGetProductTypesParams,
options?: UseQueryOptionsWrapper<
Response<AdminProductTypesListRes>,
@@ -1,2 +1,16 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Product API Routes](https://docs.medusajs.com/api/admin#products).
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* Products are saleable items in a store. This also includes [saleable gift cards](https://docs.medusajs.com/modules/gift-cards/admin/manage-gift-cards#manage-gift-card-product) in a store.
*
* Related Guide: [How to manage products](https://docs.medusajs.com/modules/products/admin/manage-products).
*
* @customNamespace Hooks.Admin.Products
*/
export * from "./queries"
export * from "./mutations"
@@ -20,6 +20,62 @@ import { useMedusa } from "../../../contexts"
import { buildOptions } from "../../utils/buildOptions"
import { adminProductKeys } from "./queries"
/**
* This hook creates a new Product. This hook can also be used to create a gift card if the `is_giftcard` field is set to `true`.
*
* @example
* import React from "react"
* import { useAdminCreateProduct } from "medusa-react"
*
* type CreateProductData = {
* title: string
* is_giftcard: boolean
* discountable: boolean
* options: {
* title: string
* }[]
* variants: {
* title: string
* prices: {
* amount: number
* currency_code :string
* }[]
* options: {
* value: string
* }[]
* }[],
* collection_id: string
* categories: {
* id: string
* }[]
* type: {
* value: string
* }
* tags: {
* value: string
* }[]
* }
*
* const CreateProduct = () => {
* const createProduct = useAdminCreateProduct()
* // ...
*
* const handleCreate = (productData: CreateProductData) => {
* createProduct.mutate(productData, {
* onSuccess: ({ product }) => {
* console.log(product.id)
* }
* })
* }
*
* // ...
* }
*
* export default CreateProduct
*
* @customNamespace Hooks.Admin.Products
* @category Mutations
*/
export const useAdminCreateProduct = (
options?: UseMutationOptions<
Response<AdminProductsRes>,
@@ -35,7 +91,47 @@ export const useAdminCreateProduct = (
)
}
/**
* This hook updates a Product's details.
*
* @example
* import React from "react"
* import { useAdminUpdateProduct } from "medusa-react"
*
* type Props = {
* productId: string
* }
*
* const Product = ({ productId }: Props) => {
* const updateProduct = useAdminUpdateProduct(
* productId
* )
* // ...
*
* const handleUpdate = (
* title: string
* ) => {
* updateProduct.mutate({
* title,
* }, {
* onSuccess: ({ product }) => {
* console.log(product.id)
* }
* })
* }
*
* // ...
* }
*
* export default Product
*
* @customNamespace Hooks.Admin.Products
* @category Mutations
*/
export const useAdminUpdateProduct = (
/**
* The product's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminProductsRes>,
@@ -57,7 +153,43 @@ export const useAdminUpdateProduct = (
)
}
/**
* This hook deletes a product and its associated product variants and options.
*
* @example
* import React from "react"
* import { useAdminDeleteProduct } from "medusa-react"
*
* type Props = {
* productId: string
* }
*
* const Product = ({ productId }: Props) => {
* const deleteProduct = useAdminDeleteProduct(
* productId
* )
* // ...
*
* const handleDelete = () => {
* deleteProduct.mutate(void 0, {
* onSuccess: ({ id, object, deleted}) => {
* console.log(id)
* }
* })
* }
*
* // ...
* }
*
* export default Product
*
* @customNamespace Hooks.Admin.Products
* @category Mutations
*/
export const useAdminDeleteProduct = (
/**
* The product's ID.
*/
id: string,
options?: UseMutationOptions<Response<AdminProductsDeleteRes>, Error, void>
) => {
@@ -74,7 +206,57 @@ export const useAdminDeleteProduct = (
)
}
/**
* This hook creates a product variant associated with a product. Each product variant must have a unique combination of product option values.
*
* @example
* import React from "react"
* import { useAdminCreateVariant } from "medusa-react"
*
* type CreateVariantData = {
* title: string
* prices: {
* amount: number
* currency_code: string
* }[]
* options: {
* option_id: string
* value: string
* }[]
* }
*
* type Props = {
* productId: string
* }
*
* const CreateProductVariant = ({ productId }: Props) => {
* const createVariant = useAdminCreateVariant(
* productId
* )
* // ...
*
* const handleCreate = (
* variantData: CreateVariantData
* ) => {
* createVariant.mutate(variantData, {
* onSuccess: ({ product }) => {
* console.log(product.variants)
* }
* })
* }
*
* // ...
* }
*
* export default CreateProductVariant
*
* @customNamespace Hooks.Admin.Products
* @category Mutations
*/
export const useAdminCreateVariant = (
/**
* The product's ID.
*/
productId: string,
options?: UseMutationOptions<
Response<AdminProductsRes>,
@@ -96,12 +278,62 @@ export const useAdminCreateVariant = (
)
}
export type AdminUpdateVariantReq = AdminPostProductsProductVariantsVariantReq & {
/**
* The product variant's ID.
*/
variant_id: string
}
/**
* This hook updates a product variant's details.
*
* @example
* import React from "react"
* import { useAdminUpdateVariant } from "medusa-react"
*
* type Props = {
* productId: string
* variantId: string
* }
*
* const ProductVariant = ({
* productId,
* variantId
* }: Props) => {
* const updateVariant = useAdminUpdateVariant(
* productId
* )
* // ...
*
* const handleUpdate = (title: string) => {
* updateVariant.mutate({
* variant_id: variantId,
* title,
* }, {
* onSuccess: ({ product }) => {
* console.log(product.variants)
* }
* })
* }
*
* // ...
* }
*
* export default ProductVariant
*
* @customNamespace Hooks.Admin.Products
* @category Mutations
*/
export const useAdminUpdateVariant = (
/**
* The product's ID.
*/
productId: string,
options?: UseMutationOptions<
Response<AdminProductsRes>,
Error,
AdminPostProductsProductVariantsVariantReq & { variant_id: string }
AdminUpdateVariantReq
>
) => {
const { client } = useMedusa()
@@ -111,7 +343,7 @@ export const useAdminUpdateVariant = (
({
variant_id,
...payload
}: AdminPostProductsProductVariantsVariantReq & { variant_id: string }) =>
}: AdminUpdateVariantReq) =>
client.admin.products.updateVariant(productId, variant_id, payload),
buildOptions(
queryClient,
@@ -121,7 +353,49 @@ export const useAdminUpdateVariant = (
)
}
/**
* This hook deletes a product variant.
*
* @typeParamDefinition string - The ID of the product variant to delete.
*
* @example
* import React from "react"
* import { useAdminDeleteVariant } from "medusa-react"
*
* type Props = {
* productId: string
* variantId: string
* }
*
* const ProductVariant = ({
* productId,
* variantId
* }: Props) => {
* const deleteVariant = useAdminDeleteVariant(
* productId
* )
* // ...
*
* const handleDelete = () => {
* deleteVariant.mutate(variantId, {
* onSuccess: ({ variant_id, object, deleted, product }) => {
* console.log(product.variants)
* }
* })
* }
*
* // ...
* }
*
* export default ProductVariant
*
* @customNamespace Hooks.Admin.Products
* @category Mutations
*/
export const useAdminDeleteVariant = (
/**
* The product's ID.
*/
productId: string,
options?: UseMutationOptions<
Response<AdminProductsDeleteVariantRes>,
@@ -143,7 +417,47 @@ export const useAdminDeleteVariant = (
)
}
/**
* This hook adds a product option to a product.
*
* @example
* import React from "react"
* import { useAdminCreateProductOption } from "medusa-react"
*
* type Props = {
* productId: string
* }
*
* const CreateProductOption = ({ productId }: Props) => {
* const createOption = useAdminCreateProductOption(
* productId
* )
* // ...
*
* const handleCreate = (
* title: string
* ) => {
* createOption.mutate({
* title
* }, {
* onSuccess: ({ product }) => {
* console.log(product.options)
* }
* })
* }
*
* // ...
* }
*
* export default CreateProductOption
*
* @customNamespace Hooks.Admin.Products
* @category Mutations
*/
export const useAdminCreateProductOption = (
/**
* The product's ID.
*/
productId: string,
options?: UseMutationOptions<
Response<AdminProductsRes>,
@@ -161,12 +475,64 @@ export const useAdminCreateProductOption = (
)
}
export type AdminUpdateProductOptionReq = AdminPostProductsProductOptionsOption & {
/**
* The ID of the product option to update.
*/
option_id: string
}
/**
* This hook updates a product option's details.
*
* @example
* import React from "react"
* import { useAdminUpdateProductOption } from "medusa-react"
*
* type Props = {
* productId: string
* optionId: string
* }
*
* const ProductOption = ({
* productId,
* optionId
* }: Props) => {
* const updateOption = useAdminUpdateProductOption(
* productId
* )
* // ...
*
* const handleUpdate = (
* title: string
* ) => {
* updateOption.mutate({
* option_id: optionId,
* title,
* }, {
* onSuccess: ({ product }) => {
* console.log(product.options)
* }
* })
* }
*
* // ...
* }
*
* export default ProductOption
*
* @customNamespace Hooks.Admin.Products
* @category Mutations
*/
export const useAdminUpdateProductOption = (
/**
* The product's ID.
*/
productId: string,
options?: UseMutationOptions<
Response<AdminProductsRes>,
Error,
AdminPostProductsProductOptionsOption & { option_id: string }
AdminUpdateProductOptionReq
>
) => {
const { client } = useMedusa()
@@ -176,13 +542,56 @@ export const useAdminUpdateProductOption = (
({
option_id,
...payload
}: AdminPostProductsProductOptionsOption & { option_id: string }) =>
}: AdminUpdateProductOptionReq) =>
client.admin.products.updateOption(productId, option_id, payload),
buildOptions(queryClient, adminProductKeys.detail(productId), options)
)
}
/**
* This hook deletes a product option. If there are product variants that use this product option,
* they must be deleted before deleting the product option.
*
* @typeParamDefinition string - The ID of the product option to delete.
*
* @example
* import React from "react"
* import { useAdminDeleteProductOption } from "medusa-react"
*
* type Props = {
* productId: string
* optionId: string
* }
*
* const ProductOption = ({
* productId,
* optionId
* }: Props) => {
* const deleteOption = useAdminDeleteProductOption(
* productId
* )
* // ...
*
* const handleDelete = () => {
* deleteOption.mutate(optionId, {
* onSuccess: ({ option_id, object, deleted, product }) => {
* console.log(product.options)
* }
* })
* }
*
* // ...
* }
*
* export default ProductOption
*
* @customNamespace Hooks.Admin.Products
* @category Mutations
*/
export const useAdminDeleteProductOption = (
/**
* The product's ID.
*/
productId: string,
options?: UseMutationOptions<
Response<AdminProductsDeleteOptionRes>,
@@ -17,7 +17,110 @@ export const adminProductKeys = queryKeysFactory(ADMIN_PRODUCTS_QUERY_KEY)
type ProductQueryKeys = typeof adminProductKeys
/**
* This hook retrieves a list of products. The products can be filtered by fields such as `q` or `status` passed in
* the `query` parameter. The products can also be sorted or paginated.
*
* @example
* To list products:
*
* ```tsx
* import React from "react"
* import { useAdminProducts } from "medusa-react"
*
* const Products = () => {
* const { products, isLoading } = useAdminProducts()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {products && !products.length && <span>No Products</span>}
* {products && products.length > 0 && (
* <ul>
* {products.map((product) => (
* <li key={product.id}>{product.title}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default Products
* ```
*
* To specify relations that should be retrieved within the products:
*
* ```tsx
* import React from "react"
* import { useAdminProducts } from "medusa-react"
*
* const Products = () => {
* const { products, isLoading } = useAdminProducts({
* expand: "images"
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {products && !products.length && <span>No Products</span>}
* {products && products.length > 0 && (
* <ul>
* {products.map((product) => (
* <li key={product.id}>{product.title}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default Products
* ```
*
* By default, only the first `50` records are retrieved. You can control pagination by specifying the `limit` and `offset` properties:
*
* ```tsx
* import React from "react"
* import { useAdminProducts } from "medusa-react"
*
* const Products = () => {
* const {
* products,
* limit,
* offset,
* isLoading
* } = useAdminProducts({
* expand: "images",
* limit: 20,
* offset: 0
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {products && !products.length && <span>No Products</span>}
* {products && products.length > 0 && (
* <ul>
* {products.map((product) => (
* <li key={product.id}>{product.title}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default Products
* ```
*
* @customNamespace Hooks.Admin.Products
* @category Queries
*/
export const useAdminProducts = (
/**
* Filters and pagination configurations to apply on the retrieved products.
*/
query?: AdminGetProductsParams,
options?: UseQueryOptionsWrapper<
Response<AdminProductsListRes>,
@@ -34,8 +137,45 @@ export const useAdminProducts = (
return { ...data, ...rest } as const
}
/**
* This hook retrieves a product's details.
*
* @example
* import React from "react"
* import { useAdminProduct } from "medusa-react"
*
* type Props = {
* productId: string
* }
*
* const Product = ({ productId }: Props) => {
* const {
* product,
* isLoading,
* } = useAdminProduct(productId)
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {product && <span>{product.title}</span>}
*
* </div>
* )
* }
*
* export default Product
*
* @customNamespace Hooks.Admin.Products
* @category Queries
*/
export const useAdminProduct = (
/**
* The product's ID.
*/
id: string,
/**
* Configurations to apply on the retrieved product.
*/
query?: AdminGetProductParams,
options?: UseQueryOptionsWrapper<
Response<AdminProductsRes>,
@@ -52,6 +192,36 @@ export const useAdminProduct = (
return { ...data, ...rest } as const
}
/**
* This hook retrieves a list of Product Tags with how many times each is used in products.
*
* @example
* import React from "react"
* import { useAdminProductTagUsage } from "medusa-react"
*
* const ProductTags = (productId: string) => {
* const { tags, isLoading } = useAdminProductTagUsage()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {tags && !tags.length && <span>No Product Tags</span>}
* {tags && tags.length > 0 && (
* <ul>
* {tags.map((tag) => (
* <li key={tag.id}>{tag.value} - {tag.usage_count}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default ProductTags
*
* @customNamespace Hooks.Admin.Products
* @category Queries
*/
export const useAdminProductTagUsage = (
options?: UseQueryOptionsWrapper<
Response<AdminProductsListTagsRes>,
@@ -1,2 +1,22 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Publishable API Key API Routes](https://docs.medusajs.com/api/admin#publishable-api-keys).
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* Publishable API Keys can be used to scope Store API calls with an API key, determining what resources are retrieved when querying the API.
* For example, a publishable API key can be associated with one or more sales channels.
*
* When it is passed in the header of a request to the List Product store API Route,
* the sales channels are inferred from the key and only products associated with those sales channels are retrieved.
*
* Admins can manage publishable API keys and their associated resources. Currently, only Sales Channels are supported as a resource.
*
* Related Guide: [How to manage publishable API keys](https://docs.medusajs.com/development/publishable-api-keys/admin/manage-publishable-api-keys).
*
* @customNamespace Hooks.Admin.Publishable API Keys
*/
export * from "./queries"
export * from "./mutations"
@@ -6,6 +6,7 @@ import {
} from "@tanstack/react-query"
import {
AdminDeletePublishableApiKeySalesChannelsBatchReq,
AdminPostPublishableApiKeySalesChannelsBatchReq,
AdminPostPublishableApiKeysPublishableApiKeyReq,
AdminPostPublishableApiKeysReq,
@@ -17,6 +18,35 @@ import { useMedusa } from "../../../contexts"
import { buildOptions } from "../../utils/buildOptions"
import { adminPublishableApiKeysKeys } from "./queries"
/**
* This hook creates a publishable API key.
*
* @example
* import React from "react"
* import { useAdminCreatePublishableApiKey } from "medusa-react"
*
* const CreatePublishableApiKey = () => {
* const createKey = useAdminCreatePublishableApiKey()
* // ...
*
* const handleCreate = (title: string) => {
* createKey.mutate({
* title,
* }, {
* onSuccess: ({ publishable_api_key }) => {
* console.log(publishable_api_key.id)
* }
* })
* }
*
* // ...
* }
*
* export default CreatePublishableApiKey
*
* @customNamespace Hooks.Admin.Publishable API Keys
* @category Mutations
*/
export const useAdminCreatePublishableApiKey = (
options?: UseMutationOptions<
Response<AdminPublishableApiKeysRes>,
@@ -33,7 +63,47 @@ export const useAdminCreatePublishableApiKey = (
)
}
/**
* This hook updates a publishable API key's details.
*
* @example
* import React from "react"
* import { useAdminUpdatePublishableApiKey } from "medusa-react"
*
* type Props = {
* publishableApiKeyId: string
* }
*
* const PublishableApiKey = ({
* publishableApiKeyId
* }: Props) => {
* const updateKey = useAdminUpdatePublishableApiKey(
* publishableApiKeyId
* )
* // ...
*
* const handleUpdate = (title: string) => {
* updateKey.mutate({
* title,
* }, {
* onSuccess: ({ publishable_api_key }) => {
* console.log(publishable_api_key.id)
* }
* })
* }
*
* // ...
* }
*
* export default PublishableApiKey
*
* @customNamespace Hooks.Admin.Publishable API Keys
* @category Mutations
*/
export const useAdminUpdatePublishableApiKey = (
/**
* The publishable API key's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminPublishableApiKeysRes>,
@@ -59,7 +129,45 @@ export const useAdminUpdatePublishableApiKey = (
)
}
/**
* This hook deletes a publishable API key. Associated resources, such as sales channels, are not deleted.
*
* @example
* import React from "react"
* import { useAdminDeletePublishableApiKey } from "medusa-react"
*
* type Props = {
* publishableApiKeyId: string
* }
*
* const PublishableApiKey = ({
* publishableApiKeyId
* }: Props) => {
* const deleteKey = useAdminDeletePublishableApiKey(
* publishableApiKeyId
* )
* // ...
*
* const handleDelete = () => {
* deleteKey.mutate(void 0, {
* onSuccess: ({ id, object, deleted }) => {
* console.log(id)
* }
* })
* }
*
* // ...
* }
*
* export default PublishableApiKey
*
* @customNamespace Hooks.Admin.Publishable API Keys
* @category Mutations
*/
export const useAdminDeletePublishableApiKey = (
/**
* The publishable API key's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminPublishableApiKeyDeleteRes>,
@@ -83,7 +191,45 @@ export const useAdminDeletePublishableApiKey = (
)
}
/**
* This hook revokes a publishable API key. Revoking the publishable API Key can't be undone, and the key can't be used in future requests.
*
* @example
* import React from "react"
* import { useAdminRevokePublishableApiKey } from "medusa-react"
*
* type Props = {
* publishableApiKeyId: string
* }
*
* const PublishableApiKey = ({
* publishableApiKeyId
* }: Props) => {
* const revokeKey = useAdminRevokePublishableApiKey(
* publishableApiKeyId
* )
* // ...
*
* const handleRevoke = () => {
* revokeKey.mutate(void 0, {
* onSuccess: ({ publishable_api_key }) => {
* console.log(publishable_api_key.revoked_at)
* }
* })
* }
*
* // ...
* }
*
* export default PublishableApiKey
*
* @customNamespace Hooks.Admin.Publishable API Keys
* @category Mutations
*/
export const useAdminRevokePublishableApiKey = (
/**
* The publishable API key's ID.
*/
id: string,
options?: UseMutationOptions<Response<AdminPublishableApiKeysRes>, Error>
) => {
@@ -103,7 +249,54 @@ export const useAdminRevokePublishableApiKey = (
)
}
/**
* This hook adds a list of sales channels to a publishable API key.
*
* @example
* import React from "react"
* import {
* useAdminAddPublishableKeySalesChannelsBatch,
* } from "medusa-react"
*
* type Props = {
* publishableApiKeyId: string
* }
*
* const PublishableApiKey = ({
* publishableApiKeyId
* }: Props) => {
* const addSalesChannels =
* useAdminAddPublishableKeySalesChannelsBatch(
* publishableApiKeyId
* )
* // ...
*
* const handleAdd = (salesChannelId: string) => {
* addSalesChannels.mutate({
* sales_channel_ids: [
* {
* id: salesChannelId,
* },
* ],
* }, {
* onSuccess: ({ publishable_api_key }) => {
* console.log(publishable_api_key.id)
* }
* })
* }
*
* // ...
* }
*
* export default PublishableApiKey
*
* @customNamespace Hooks.Admin.Publishable API Keys
* @category Mutations
*/
export const useAdminAddPublishableKeySalesChannelsBatch = (
/**
* The publishable API key's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminPublishableApiKeysRes>,
@@ -125,19 +318,67 @@ export const useAdminAddPublishableKeySalesChannelsBatch = (
)
}
/**
* This hook removes a list of sales channels from a publishable API key. This doesn't delete the sales channels and only
* removes the association between them and the publishable API key.
*
* @example
* import React from "react"
* import {
* useAdminRemovePublishableKeySalesChannelsBatch,
* } from "medusa-react"
*
* type Props = {
* publishableApiKeyId: string
* }
*
* const PublishableApiKey = ({
* publishableApiKeyId
* }: Props) => {
* const deleteSalesChannels =
* useAdminRemovePublishableKeySalesChannelsBatch(
* publishableApiKeyId
* )
* // ...
*
* const handleDelete = (salesChannelId: string) => {
* deleteSalesChannels.mutate({
* sales_channel_ids: [
* {
* id: salesChannelId,
* },
* ],
* }, {
* onSuccess: ({ publishable_api_key }) => {
* console.log(publishable_api_key.id)
* }
* })
* }
*
* // ...
* }
*
* export default PublishableApiKey
*
* @customNamespace Hooks.Admin.Publishable API Keys
* @category Mutations
*/
export const useAdminRemovePublishableKeySalesChannelsBatch = (
/**
* The publishable API key's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminPublishableApiKeysRes>,
Error,
AdminPostPublishableApiKeySalesChannelsBatchReq
AdminDeletePublishableApiKeySalesChannelsBatchReq
>
) => {
const { client } = useMedusa()
const queryClient = useQueryClient()
return useMutation(
(payload: AdminPostPublishableApiKeySalesChannelsBatchReq) =>
(payload: AdminDeletePublishableApiKeySalesChannelsBatchReq) =>
client.admin.publishableApiKeys.deleteSalesChannelsBatch(id, payload),
buildOptions(
queryClient,
@@ -28,9 +28,46 @@ export const adminPublishableApiKeysKeys = {
type PublishableApiKeyQueryKeys = typeof adminPublishableApiKeysKeys
/**
* This hook retrieves a publishable API key's details.
*
* @example
* import React from "react"
* import {
* useAdminPublishableApiKey,
* } from "medusa-react"
*
* type Props = {
* publishableApiKeyId: string
* }
*
* const PublishableApiKey = ({
* publishableApiKeyId
* }: Props) => {
* const { publishable_api_key, isLoading } =
* useAdminPublishableApiKey(
* publishableApiKeyId
* )
*
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {publishable_api_key && <span>{publishable_api_key.title}</span>}
* </div>
* )
* }
*
* export default PublishableApiKey
*
* @customNamespace Hooks.Admin.Publishable API Keys
* @category Queries
*/
export const useAdminPublishableApiKey = (
/**
* The publishable API key's ID.
*/
id: string,
query?: GetPublishableApiKeysParams,
options?: UseQueryOptionsWrapper<
Response<AdminPublishableApiKeysRes>,
Error,
@@ -40,13 +77,104 @@ export const useAdminPublishableApiKey = (
const { client } = useMedusa()
const { data, ...rest } = useQuery(
adminPublishableApiKeysKeys.detail(id),
() => client.admin.publishableApiKeys.retrieve(id, query),
() => client.admin.publishableApiKeys.retrieve(id),
options
)
return { ...data, ...rest } as const
}
/**
* This hook retrieves a list of publishable API keys. The publishable API keys can be filtered by fields such as `q` passed in `query`.
* The publishable API keys can also be paginated.
*
* @example
* To list publishable API keys:
*
* ```tsx
* import React from "react"
* import { PublishableApiKey } from "@medusajs/medusa"
* import { useAdminPublishableApiKeys } from "medusa-react"
*
* const PublishableApiKeys = () => {
* const { publishable_api_keys, isLoading } =
* useAdminPublishableApiKeys()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {publishable_api_keys && !publishable_api_keys.length && (
* <span>No Publishable API Keys</span>
* )}
* {publishable_api_keys &&
* publishable_api_keys.length > 0 && (
* <ul>
* {publishable_api_keys.map(
* (publishableApiKey: PublishableApiKey) => (
* <li key={publishableApiKey.id}>
* {publishableApiKey.title}
* </li>
* )
* )}
* </ul>
* )}
* </div>
* )
* }
*
* export default PublishableApiKeys
* ```
*
* By default, only the first `20` records are retrieved. You can control pagination by specifying the `limit` and `offset` properties:
*
* ```tsx
* import React from "react"
* import { PublishableApiKey } from "@medusajs/medusa"
* import { useAdminPublishableApiKeys } from "medusa-react"
*
* const PublishableApiKeys = () => {
* const {
* publishable_api_keys,
* limit,
* offset,
* isLoading
* } =
* useAdminPublishableApiKeys({
* limit: 50,
* offset: 0
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {publishable_api_keys && !publishable_api_keys.length && (
* <span>No Publishable API Keys</span>
* )}
* {publishable_api_keys &&
* publishable_api_keys.length > 0 && (
* <ul>
* {publishable_api_keys.map(
* (publishableApiKey: PublishableApiKey) => (
* <li key={publishableApiKey.id}>
* {publishableApiKey.title}
* </li>
* )
* )}
* </ul>
* )}
* </div>
* )
* }
*
* export default PublishableApiKeys
* ```
*
* @customNamespace Hooks.Admin.Publishable API Keys
* @category Queries
*/
export const useAdminPublishableApiKeys = (
/**
* Filters and pagination configurations to apply on the retrieved publishable API keys.
*/
query?: GetPublishableApiKeysParams,
options?: UseQueryOptionsWrapper<
Response<AdminPublishableApiKeysListRes>,
@@ -63,8 +191,58 @@ export const useAdminPublishableApiKeys = (
return { ...data, ...rest } as const
}
/**
* This hook lists the sales channels associated with a publishable API key. The sales channels can be
* filtered by fields such as `q` passed in the `query` parameter.
*
* @example
* import React from "react"
* import {
* useAdminPublishableApiKeySalesChannels,
* } from "medusa-react"
*
* type Props = {
* publishableApiKeyId: string
* }
*
* const SalesChannels = ({
* publishableApiKeyId
* }: Props) => {
* const { sales_channels, isLoading } =
* useAdminPublishableApiKeySalesChannels(
* publishableApiKeyId
* )
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {sales_channels && !sales_channels.length && (
* <span>No Sales Channels</span>
* )}
* {sales_channels && sales_channels.length > 0 && (
* <ul>
* {sales_channels.map((salesChannel) => (
* <li key={salesChannel.id}>{salesChannel.name}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default SalesChannels
*
* @customNamespace Hooks.Admin.Publishable API Keys
* @category Queries
*/
export const useAdminPublishableApiKeySalesChannels = (
/**
* The publishable API Key's ID.
*/
id: string,
/**
* Filters to apply on the retrieved sales channels.
*/
query?: GetPublishableApiKeySalesChannelsParams,
options?: UseQueryOptionsWrapper<
Response<AdminPublishableApiKeysListSalesChannelsRes>,
@@ -1,2 +1,17 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Region API Routes](https://docs.medusajs.com/api/admin#regions).
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* Regions are different countries or geographical regions that the commerce store serves customers in.
* Admins can manage these regions, their providers, and more.
*
* Related Guide: [How to manage regions](https://docs.medusajs.com/modules/regions-and-currencies/admin/manage-regions).
*
* @customNamespace Hooks.Admin.Regions
*/
export * from "./queries"
export * from "./mutations"
@@ -17,6 +17,42 @@ import { useMedusa } from "../../../contexts/medusa"
import { buildOptions } from "../../utils/buildOptions"
import { adminRegionKeys } from "./queries"
/**
* This hook creates a region.
*
* @example
* import React from "react"
* import { useAdminCreateRegion } from "medusa-react"
*
* type CreateData = {
* name: string
* currency_code: string
* tax_rate: number
* payment_providers: string[]
* fulfillment_providers: string[]
* countries: string[]
* }
*
* const CreateRegion = () => {
* const createRegion = useAdminCreateRegion()
* // ...
*
* const handleCreate = (regionData: CreateData) => {
* createRegion.mutate(regionData, {
* onSuccess: ({ region }) => {
* console.log(region.id)
* }
* })
* }
*
* // ...
* }
*
* export default CreateRegion
*
* @customNamespace Hooks.Admin.Regions
* @category Mutations
*/
export const useAdminCreateRegion = (
options?: UseMutationOptions<
Response<AdminRegionsRes>,
@@ -33,7 +69,47 @@ export const useAdminCreateRegion = (
)
}
/**
* This hook updates a region's details.
*
* @example
* import React from "react"
* import { useAdminUpdateRegion } from "medusa-react"
*
* type Props = {
* regionId: string
* }
*
* const Region = ({
* regionId
* }: Props) => {
* const updateRegion = useAdminUpdateRegion(regionId)
* // ...
*
* const handleUpdate = (
* countries: string[]
* ) => {
* updateRegion.mutate({
* countries,
* }, {
* onSuccess: ({ region }) => {
* console.log(region.id)
* }
* })
* }
*
* // ...
* }
*
* export default Region
*
* @customNamespace Hooks.Admin.Regions
* @category Mutations
*/
export const useAdminUpdateRegion = (
/**
* The region's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminRegionsRes>,
@@ -55,7 +131,43 @@ export const useAdminUpdateRegion = (
)
}
/**
* This hook deletes a region. Associated resources, such as providers or currencies are not deleted. Associated tax rates are deleted.
*
* @example
* import React from "react"
* import { useAdminDeleteRegion } from "medusa-react"
*
* type Props = {
* regionId: string
* }
*
* const Region = ({
* regionId
* }: Props) => {
* const deleteRegion = useAdminDeleteRegion(regionId)
* // ...
*
* const handleDelete = () => {
* deleteRegion.mutate(void 0, {
* onSuccess: ({ id, object, deleted }) => {
* console.log(id)
* }
* })
* }
*
* // ...
* }
*
* export default Region
*
* @customNamespace Hooks.Admin.Regions
* @category Mutations
*/
export const useAdminDeleteRegion = (
/**
* The region's ID.
*/
id: string,
options?: UseMutationOptions<Response<AdminRegionsDeleteRes>, Error, void>
) => {
@@ -72,7 +184,47 @@ export const useAdminDeleteRegion = (
)
}
/**
* This hook adds a country to the list of countries in a region.
*
* @example
* import React from "react"
* import { useAdminRegionAddCountry } from "medusa-react"
*
* type Props = {
* regionId: string
* }
*
* const Region = ({
* regionId
* }: Props) => {
* const addCountry = useAdminRegionAddCountry(regionId)
* // ...
*
* const handleAddCountry = (
* countryCode: string
* ) => {
* addCountry.mutate({
* country_code: countryCode
* }, {
* onSuccess: ({ region }) => {
* console.log(region.countries)
* }
* })
* }
*
* // ...
* }
*
* export default Region
*
* @customNamespace Hooks.Admin.Regions
* @category Mutations
*/
export const useAdminRegionAddCountry = (
/**
* The region's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminRegionsRes>,
@@ -90,7 +242,47 @@ export const useAdminRegionAddCountry = (
)
}
/**
* This hook deletes a country from the list of countries in a region. The country will still be available in the system, and it can be used in other regions.
*
* @typeParamDefinition string - The code of the country to delete from the region.
*
* @example
* import React from "react"
* import { useAdminRegionRemoveCountry } from "medusa-react"
*
* type Props = {
* regionId: string
* }
*
* const Region = ({
* regionId
* }: Props) => {
* const removeCountry = useAdminRegionRemoveCountry(regionId)
* // ...
*
* const handleRemoveCountry = (
* countryCode: string
* ) => {
* removeCountry.mutate(countryCode, {
* onSuccess: ({ region }) => {
* console.log(region.countries)
* }
* })
* }
*
* // ...
* }
*
* export default Region
*
* @customNamespace Hooks.Admin.Regions
* @category Mutations
*/
export const useAdminRegionRemoveCountry = (
/**
* The region's ID.
*/
id: string,
options?: UseMutationOptions<Response<AdminRegionsRes>, Error, string>
) => {
@@ -104,7 +296,50 @@ export const useAdminRegionRemoveCountry = (
)
}
/**
* This hook adds a fulfillment provider to the list of fulfullment providers in a region.
*
* @example
* import React from "react"
* import {
* useAdminRegionAddFulfillmentProvider
* } from "medusa-react"
*
* type Props = {
* regionId: string
* }
*
* const Region = ({
* regionId
* }: Props) => {
* const addFulfillmentProvider =
* useAdminRegionAddFulfillmentProvider(regionId)
* // ...
*
* const handleAddFulfillmentProvider = (
* providerId: string
* ) => {
* addFulfillmentProvider.mutate({
* provider_id: providerId
* }, {
* onSuccess: ({ region }) => {
* console.log(region.fulfillment_providers)
* }
* })
* }
*
* // ...
* }
*
* export default Region
*
* @customNamespace Hooks.Admin.Regions
* @category Mutations
*/
export const useAdminRegionAddFulfillmentProvider = (
/**
* The region's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminRegionsRes>,
@@ -122,7 +357,50 @@ export const useAdminRegionAddFulfillmentProvider = (
)
}
/**
* This hook deletes a fulfillment provider from a region. The fulfillment provider will still be available for usage in other regions.
*
* @typeParamDefinition string - The fulfillment provider's ID to delete from the region.
*
* @example
* import React from "react"
* import {
* useAdminRegionDeleteFulfillmentProvider
* } from "medusa-react"
*
* type Props = {
* regionId: string
* }
*
* const Region = ({
* regionId
* }: Props) => {
* const removeFulfillmentProvider =
* useAdminRegionDeleteFulfillmentProvider(regionId)
* // ...
*
* const handleRemoveFulfillmentProvider = (
* providerId: string
* ) => {
* removeFulfillmentProvider.mutate(providerId, {
* onSuccess: ({ region }) => {
* console.log(region.fulfillment_providers)
* }
* })
* }
*
* // ...
* }
*
* export default Region
*
* @customNamespace Hooks.Admin.Regions
* @category Mutations
*/
export const useAdminRegionDeleteFulfillmentProvider = (
/**
* The region's ID.
*/
id: string,
options?: UseMutationOptions<Response<AdminRegionsRes>, Error, string>
) => {
@@ -136,7 +414,50 @@ export const useAdminRegionDeleteFulfillmentProvider = (
)
}
/**
* This hook adds a payment provider to the list of payment providers in a region.
*
* @example
* import React from "react"
* import {
* useAdminRegionAddPaymentProvider
* } from "medusa-react"
*
* type Props = {
* regionId: string
* }
*
* const Region = ({
* regionId
* }: Props) => {
* const addPaymentProvider =
* useAdminRegionAddPaymentProvider(regionId)
* // ...
*
* const handleAddPaymentProvider = (
* providerId: string
* ) => {
* addPaymentProvider.mutate({
* provider_id: providerId
* }, {
* onSuccess: ({ region }) => {
* console.log(region.payment_providers)
* }
* })
* }
*
* // ...
* }
*
* export default Region
*
* @customNamespace Hooks.Admin.Regions
* @category Mutations
*/
export const useAdminRegionAddPaymentProvider = (
/**
* The region's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminRegionsRes>,
@@ -154,7 +475,50 @@ export const useAdminRegionAddPaymentProvider = (
)
}
/**
* This hook deletes a payment provider from a region. The payment provider will still be available for usage in other regions.
*
* @typeParamDefinition string - The ID of the payment provider to delete from the region.
*
* @example
* import React from "react"
* import {
* useAdminRegionDeletePaymentProvider
* } from "medusa-react"
*
* type Props = {
* regionId: string
* }
*
* const Region = ({
* regionId
* }: Props) => {
* const removePaymentProvider =
* useAdminRegionDeletePaymentProvider(regionId)
* // ...
*
* const handleRemovePaymentProvider = (
* providerId: string
* ) => {
* removePaymentProvider.mutate(providerId, {
* onSuccess: ({ region }) => {
* console.log(region.payment_providers)
* }
* })
* }
*
* // ...
* }
*
* export default Region
*
* @customNamespace Hooks.Admin.Regions
* @category Mutations
*/
export const useAdminRegionDeletePaymentProvider = (
/**
* The region's ID.
*/
id: string,
options?: UseMutationOptions<Response<AdminRegionsRes>, Error, string>
) => {
@@ -16,7 +16,80 @@ export const adminRegionKeys = queryKeysFactory(ADMIN_REGIONS_QUERY_KEY)
type RegionQueryKeys = typeof adminRegionKeys
/**
* This hook retrieves a list of Regions. The regions can be filtered by fields such as `created_at` passed in the `query` parameter.
* The regions can also be paginated.
*
* @example
* To list regions:
*
* ```tsx
* import React from "react"
* import { useAdminRegions } from "medusa-react"
*
* const Regions = () => {
* const { regions, isLoading } = useAdminRegions()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {regions && !regions.length && <span>No Regions</span>}
* {regions && regions.length > 0 && (
* <ul>
* {regions.map((region) => (
* <li key={region.id}>{region.name}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default Regions
* ```
*
* By default, only the first `50` records are retrieved. You can control pagination by specifying the `limit` and `offset` properties:
*
* ```tsx
* import React from "react"
* import { useAdminRegions } from "medusa-react"
*
* const Regions = () => {
* const {
* regions,
* limit,
* offset,
* isLoading
* } = useAdminRegions({
* limit: 20,
* offset: 0
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {regions && !regions.length && <span>No Regions</span>}
* {regions && regions.length > 0 && (
* <ul>
* {regions.map((region) => (
* <li key={region.id}>{region.name}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default Regions
* ```
*
* @customNamespace Hooks.Admin.Regions
* @category Queries
*/
export const useAdminRegions = (
/**
* Filters and pagination configurations to apply on the retrieved regions.
*/
query?: AdminGetRegionsParams,
options?: UseQueryOptionsWrapper<
Response<AdminRegionsListRes>,
@@ -33,7 +106,41 @@ export const useAdminRegions = (
return { ...data, ...rest } as const
}
/**
* This hook retrieves a region's details.
*
* @example
* import React from "react"
* import { useAdminRegion } from "medusa-react"
*
* type Props = {
* regionId: string
* }
*
* const Region = ({
* regionId
* }: Props) => {
* const { region, isLoading } = useAdminRegion(
* regionId
* )
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {region && <span>{region.name}</span>}
* </div>
* )
* }
*
* export default Region
*
* @customNamespace Hooks.Admin.Regions
* @category Queries
*/
export const useAdminRegion = (
/**
* The region's ID.
*/
id: string,
options?: UseQueryOptionsWrapper<
Response<AdminRegionsRes>,
@@ -50,7 +157,58 @@ export const useAdminRegion = (
return { ...data, ...rest } as const
}
/**
* This hook retrieves a list of fulfillment options available in a region.
*
* @example
* import React from "react"
* import {
* useAdminRegionFulfillmentOptions
* } from "medusa-react"
*
* type Props = {
* regionId: string
* }
*
* const Region = ({
* regionId
* }: Props) => {
* const {
* fulfillment_options,
* isLoading
* } = useAdminRegionFulfillmentOptions(
* regionId
* )
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {fulfillment_options && !fulfillment_options.length && (
* <span>No Regions</span>
* )}
* {fulfillment_options &&
* fulfillment_options.length > 0 && (
* <ul>
* {fulfillment_options.map((option) => (
* <li key={option.provider_id}>
* {option.provider_id}
* </li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default Region
*
* @customNamespace Hooks.Admin.Regions
* @category Queries
*/
export const useAdminRegionFulfillmentOptions = (
/**
* The region's ID.
*/
regionId: string,
options?: UseQueryOptionsWrapper<
Response<AdminGetRegionsRegionFulfillmentOptionsRes>,
@@ -1,2 +1,20 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Reservation API Routes](https://docs.medusajs.com/api/admin#reservations).
* To use these hooks, make sure to install the
* [@medusajs/inventory](https://docs.medusajs.com/modules/multiwarehouse/install-modules#inventory-module) module in your Medusa backend.
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* Reservations, provided by the [Inventory Module](https://docs.medusajs.com/modules/multiwarehouse/inventory-module),
* are quantities of an item that are reserved, typically when an order is placed but not yet fulfilled.
* Reservations can be associated with any resources, but commonly with line items of an order.
*
* Related Guide: [How to manage item allocations in orders](https://docs.medusajs.com/modules/multiwarehouse/admin/manage-item-allocations-in-orders).
*
* @customNamespace Hooks.Admin.Reservations
*/
export * from "./mutations"
export * from "./queries"
@@ -17,6 +17,41 @@ import { adminInventoryItemsKeys } from "../inventory-item"
import { adminVariantKeys } from "../variants"
import { adminReservationsKeys } from "./queries"
/**
* This hook creates a reservation which can be associated with any resource, such as an order's line item.
*
* @example
* import React from "react"
* import { useAdminCreateReservation } from "medusa-react"
*
* const CreateReservation = () => {
* const createReservation = useAdminCreateReservation()
* // ...
*
* const handleCreate = (
* locationId: string,
* inventoryItemId: string,
* quantity: number
* ) => {
* createReservation.mutate({
* location_id: locationId,
* inventory_item_id: inventoryItemId,
* quantity,
* }, {
* onSuccess: ({ reservation }) => {
* console.log(reservation.id)
* }
* })
* }
*
* // ...
* }
*
* export default CreateReservation
*
* @customNamespace Hooks.Admin.Reservations
* @category Mutations
*/
export const useAdminCreateReservation = (
options?: UseMutationOptions<
Response<AdminReservationsRes>,
@@ -38,7 +73,43 @@ export const useAdminCreateReservation = (
)
}
/**
* This hook updates a reservation's details.
*
* @example
* import React from "react"
* import { useAdminUpdateReservation } from "medusa-react"
*
* type Props = {
* reservationId: string
* }
*
* const Reservation = ({ reservationId }: Props) => {
* const updateReservation = useAdminUpdateReservation(
* reservationId
* )
* // ...
*
* const handleUpdate = (
* quantity: number
* ) => {
* updateReservation.mutate({
* quantity,
* })
* }
*
* // ...
* }
*
* export default Reservation
*
* @customNamespace Hooks.Admin.Reservations
* @category Mutations
*/
export const useAdminUpdateReservation = (
/**
* The reservation's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminReservationsRes>,
@@ -65,7 +136,43 @@ export const useAdminUpdateReservation = (
)
}
/**
* This hook deletes a reservation. Associated resources, such as the line item, will not be deleted.
*
* @example
* import React from "react"
* import { useAdminDeleteReservation } from "medusa-react"
*
* type Props = {
* reservationId: string
* }
*
* const Reservation = ({ reservationId }: Props) => {
* const deleteReservation = useAdminDeleteReservation(
* reservationId
* )
* // ...
*
* const handleDelete = () => {
* deleteReservation.mutate(void 0, {
* onSuccess: ({ id, object, deleted }) => {
* console.log(id)
* }
* })
* }
*
* // ...
* }
*
* export default Reservation
*
* @customNamespace Hooks.Admin.Reservations
* @category Mutations
*/
export const useAdminDeleteReservation = (
/**
* The reservation's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminReservationsDeleteRes>,
@@ -17,7 +17,119 @@ export const adminReservationsKeys = queryKeysFactory(
type ReservationsQueryKeys = typeof adminReservationsKeys
/**
* This hook retrieves a list of reservations. The reservations can be filtered by fields such as `location_id` or `quantity`
* passed in the `query` parameter. The reservations can also be paginated.
*
* @example
* To list reservations:
*
* ```tsx
* import React from "react"
* import { useAdminReservations } from "medusa-react"
*
* const Reservations = () => {
* const { reservations, isLoading } = useAdminReservations()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {reservations && !reservations.length && (
* <span>No Reservations</span>
* )}
* {reservations && reservations.length > 0 && (
* <ul>
* {reservations.map((reservation) => (
* <li key={reservation.id}>{reservation.quantity}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default Reservations
* ```
*
* To specify relations that should be retrieved within the reservations:
*
* ```tsx
* import React from "react"
* import { useAdminReservations } from "medusa-react"
*
* const Reservations = () => {
* const {
* reservations,
* isLoading
* } = useAdminReservations({
* expand: "location"
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {reservations && !reservations.length && (
* <span>No Reservations</span>
* )}
* {reservations && reservations.length > 0 && (
* <ul>
* {reservations.map((reservation) => (
* <li key={reservation.id}>{reservation.quantity}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default Reservations
* ```
*
* By default, only the first `20` records are retrieved. You can control pagination by specifying the `limit` and `offset` properties:
*
* ```tsx
* import React from "react"
* import { useAdminReservations } from "medusa-react"
*
* const Reservations = () => {
* const {
* reservations,
* limit,
* offset,
* isLoading
* } = useAdminReservations({
* expand: "location",
* limit: 10,
* offset: 0
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {reservations && !reservations.length && (
* <span>No Reservations</span>
* )}
* {reservations && reservations.length > 0 && (
* <ul>
* {reservations.map((reservation) => (
* <li key={reservation.id}>{reservation.quantity}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default Reservations
* ```
*
* @customNamespace Hooks.Admin.Reservations
* @category Queries
*/
export const useAdminReservations = (
/**
* Filters and pagination parameters to apply on the retrieved reservations.
*/
query?: AdminGetReservationsParams,
options?: UseQueryOptionsWrapper<
Response<AdminReservationsListRes>,
@@ -36,7 +148,41 @@ export const useAdminReservations = (
return { ...data, ...rest } as const
}
/**
* This hook retrieves a reservation's details.
*
* @example
* import React from "react"
* import { useAdminReservation } from "medusa-react"
*
* type Props = {
* reservationId: string
* }
*
* const Reservation = ({ reservationId }: Props) => {
* const { reservation, isLoading } = useAdminReservation(
* reservationId
* )
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {reservation && (
* <span>{reservation.inventory_item_id}</span>
* )}
* </div>
* )
* }
*
* export default Reservation
*
* @customNamespace Hooks.Admin.Reservations
* @category Queries
*/
export const useAdminReservation = (
/**
* The reservation's ID.
*/
id: string,
options?: UseQueryOptionsWrapper<
Response<AdminReservationsRes>,
@@ -1,2 +1,17 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Return Reason API Routes](https://docs.medusajs.com/api/admin#return-reasons).
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* Return reasons are key-value pairs that are used to specify why an order return is being created.
* Admins can manage available return reasons, and they can be used by both admins and customers when creating a return.
*
* Related Guide: [How to manage return reasons](https://docs.medusajs.com/modules/orders/admin/manage-returns#manage-return-reasons).
*
* @customNamespace Hooks.Admin.Return Reasons
*/
export * from "./queries"
export * from "./mutations"
@@ -13,6 +13,39 @@ import { useMedusa } from "../../../contexts/medusa"
import { buildOptions } from "../../utils/buildOptions"
import { adminReturnReasonKeys } from "./queries"
/**
* This hook creates a return reason.
*
* @example
* import React from "react"
* import { useAdminCreateReturnReason } from "medusa-react"
*
* const CreateReturnReason = () => {
* const createReturnReason = useAdminCreateReturnReason()
* // ...
*
* const handleCreate = (
* label: string,
* value: string
* ) => {
* createReturnReason.mutate({
* label,
* value,
* }, {
* onSuccess: ({ return_reason }) => {
* console.log(return_reason.id)
* }
* })
* }
*
* // ...
* }
*
* export default CreateReturnReason
*
* @customNamespace Hooks.Admin.Return Reasons
* @category Mutations
*/
export const useAdminCreateReturnReason = (
options?: UseMutationOptions<
Response<AdminReturnReasonsRes>,
@@ -30,7 +63,47 @@ export const useAdminCreateReturnReason = (
)
}
/**
* This hook updates a return reason's details.
*
* @example
* import React from "react"
* import { useAdminUpdateReturnReason } from "medusa-react"
*
* type Props = {
* returnReasonId: string
* }
*
* const ReturnReason = ({ returnReasonId }: Props) => {
* const updateReturnReason = useAdminUpdateReturnReason(
* returnReasonId
* )
* // ...
*
* const handleUpdate = (
* label: string
* ) => {
* updateReturnReason.mutate({
* label,
* }, {
* onSuccess: ({ return_reason }) => {
* console.log(return_reason.label)
* }
* })
* }
*
* // ...
* }
*
* export default ReturnReason
*
* @customNamespace Hooks.Admin.Return Reasons
* @category Mutations
*/
export const useAdminUpdateReturnReason = (
/**
* The return reason's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminReturnReasonsRes>,
@@ -52,7 +125,43 @@ export const useAdminUpdateReturnReason = (
)
}
/**
* This hook deletes a return reason.
*
* @example
* import React from "react"
* import { useAdminDeleteReturnReason } from "medusa-react"
*
* type Props = {
* returnReasonId: string
* }
*
* const ReturnReason = ({ returnReasonId }: Props) => {
* const deleteReturnReason = useAdminDeleteReturnReason(
* returnReasonId
* )
* // ...
*
* const handleDelete = () => {
* deleteReturnReason.mutate(void 0, {
* onSuccess: ({ id, object, deleted }) => {
* console.log(id)
* }
* })
* }
*
* // ...
* }
*
* export default ReturnReason
*
* @customNamespace Hooks.Admin.Return Reasons
* @category Mutations
*/
export const useAdminDeleteReturnReason = (
/**
* The return reason's ID.
*/
id: string,
options?: UseMutationOptions
) => {
@@ -16,6 +16,40 @@ export const adminReturnReasonKeys = queryKeysFactory(
type ReturnReasonQueryKeys = typeof adminReturnReasonKeys
/**
* This hook retrieves a list of return reasons.
*
* @example
* import React from "react"
* import { useAdminReturnReasons } from "medusa-react"
*
* const ReturnReasons = () => {
* const { return_reasons, isLoading } = useAdminReturnReasons()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {return_reasons && !return_reasons.length && (
* <span>No Return Reasons</span>
* )}
* {return_reasons && return_reasons.length > 0 && (
* <ul>
* {return_reasons.map((reason) => (
* <li key={reason.id}>
* {reason.label}: {reason.value}
* </li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default ReturnReasons
*
* @customNamespace Hooks.Admin.Return Reasons
* @category Queries
*/
export const useAdminReturnReasons = (
options?: UseQueryOptionsWrapper<
Response<AdminReturnReasonsListRes>,
@@ -32,7 +66,39 @@ export const useAdminReturnReasons = (
return { ...data, ...rest } as const
}
/**
* This hook retrieves a return reason's details.
*
* @example
* import React from "react"
* import { useAdminReturnReason } from "medusa-react"
*
* type Props = {
* returnReasonId: string
* }
*
* const ReturnReason = ({ returnReasonId }: Props) => {
* const { return_reason, isLoading } = useAdminReturnReason(
* returnReasonId
* )
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {return_reason && <span>{return_reason.label}</span>}
* </div>
* )
* }
*
* export default ReturnReason
*
* @customNamespace Hooks.Admin.Return Reasons
* @category Queries
*/
export const useAdminReturnReason = (
/**
* The return reason's ID.
*/
id: string,
options?: UseQueryOptionsWrapper<
Response<AdminReturnReasonsRes>,
@@ -1,2 +1,17 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Return API Routes](https://docs.medusajs.com/api/admin#returns).
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* A return can be created by a customer or an admin to return items in an order.
* Admins can manage these returns and change their state.
*
* Related Guide: [How to manage returns](https://docs.medusajs.com/modules/orders/admin/manage-returns).
*
* @customNamespace Hooks.Admin.Returns
*/
export * from "./queries"
export * from "./mutations"
@@ -13,7 +13,50 @@ import { useMedusa } from "../../../contexts/medusa"
import { buildOptions } from "../../utils/buildOptions"
import { adminReturnKeys } from "./queries"
/**
* This hook marks a return as received. This also updates the status of associated order, claim, or swap accordingly.
*
* @example
* import React from "react"
* import { useAdminReceiveReturn } from "medusa-react"
*
* type ReceiveReturnData = {
* items: {
* item_id: string
* quantity: number
* }[]
* }
*
* type Props = {
* returnId: string
* }
*
* const Return = ({ returnId }: Props) => {
* const receiveReturn = useAdminReceiveReturn(
* returnId
* )
* // ...
*
* const handleReceive = (data: ReceiveReturnData) => {
* receiveReturn.mutate(data, {
* onSuccess: ({ return: dataReturn }) => {
* console.log(dataReturn.status)
* }
* })
* }
*
* // ...
* }
*
* export default Return
*
* @customNamespace Hooks.Admin.Returns
* @category Mutations
*/
export const useAdminReceiveReturn = (
/**
* The return's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminReturnsRes>,
@@ -34,7 +77,43 @@ export const useAdminReceiveReturn = (
)
}
/**
* This hook registers a return as canceled. The return can be associated with an order, claim, or swap.
*
* @example
* import React from "react"
* import { useAdminCancelReturn } from "medusa-react"
*
* type Props = {
* returnId: string
* }
*
* const Return = ({ returnId }: Props) => {
* const cancelReturn = useAdminCancelReturn(
* returnId
* )
* // ...
*
* const handleCancel = () => {
* cancelReturn.mutate(void 0, {
* onSuccess: ({ order }) => {
* console.log(order.returns)
* }
* })
* }
*
* // ...
* }
*
* export default Return
*
* @customNamespace Hooks.Admin.Returns
* @category Mutations
*/
export const useAdminCancelReturn = (
/**
* The return's ID.
*/
id: string,
options?: UseMutationOptions<Response<AdminReturnsCancelRes>, Error, void>
) => {
@@ -11,6 +11,40 @@ export const adminReturnKeys = queryKeysFactory(ADMIN_RETURNS_QUERY_KEY)
type ReturnQueryKeys = typeof adminReturnKeys
/**
* This hook retrieves a list of Returns. The returns can be paginated.
*
* @example
* import React from "react"
* import { useAdminReturns } from "medusa-react"
*
* const Returns = () => {
* const { returns, isLoading } = useAdminReturns()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {returns && !returns.length && (
* <span>No Returns</span>
* )}
* {returns && returns.length > 0 && (
* <ul>
* {returns.map((returnData) => (
* <li key={returnData.id}>
* {returnData.status}
* </li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default Returns
*
* @customNamespace Hooks.Admin.Returns
* @category Queries
*/
export const useAdminReturns = (
options?: UseQueryOptionsWrapper<
Response<AdminReturnsListRes>,
@@ -1,2 +1,17 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Sales Channel API Routes](https://docs.medusajs.com/api/admin#sales-channels).
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* A sales channel indicates a channel where products can be sold in. For example, a webshop or a mobile app.
* Admins can manage sales channels and the products available in them.
*
* Related Guide: [How to manage sales channels](https://docs.medusajs.com/modules/sales-channels/admin/manage).
*
* @customNamespace Hooks.Admin.Sales Channels
*/
export * from "./queries"
export * from "./mutations"
@@ -20,10 +20,34 @@ import { adminStockLocationsKeys } from "../stock-locations"
import { adminSalesChannelsKeys } from "./queries"
/**
* Hook provides a mutation function for creating sales channel.
*
* @experimental This feature is under development and may change in the future.
* To use this feature please enable the corresponding feature flag in your medusa backend project.
* This hook creates a sales channel.
*
* @example
* import React from "react"
* import { useAdminCreateSalesChannel } from "medusa-react"
*
* const CreateSalesChannel = () => {
* const createSalesChannel = useAdminCreateSalesChannel()
* // ...
*
* const handleCreate = (name: string, description: string) => {
* createSalesChannel.mutate({
* name,
* description,
* }, {
* onSuccess: ({ sales_channel }) => {
* console.log(sales_channel.id)
* }
* })
* }
*
* // ...
* }
*
* export default CreateSalesChannel
*
* @customNamespace Hooks.Admin.Sales Channels
* @category Mutations
*/
export const useAdminCreateSalesChannel = (
options?: UseMutationOptions<
@@ -42,13 +66,47 @@ export const useAdminCreateSalesChannel = (
)
}
/** update a sales channel
* @experimental This feature is under development and may change in the future.
* To use this feature please enable feature flag `sales_channels` in your medusa backend project.
* @description updates a sales channel
* @returns the updated medusa sales channel
/**
* This hook updates a sales channel's details.
*
* @example
* import React from "react"
* import { useAdminUpdateSalesChannel } from "medusa-react"
*
* type Props = {
* salesChannelId: string
* }
*
* const SalesChannel = ({ salesChannelId }: Props) => {
* const updateSalesChannel = useAdminUpdateSalesChannel(
* salesChannelId
* )
* // ...
*
* const handleUpdate = (
* is_disabled: boolean
* ) => {
* updateSalesChannel.mutate({
* is_disabled,
* }, {
* onSuccess: ({ sales_channel }) => {
* console.log(sales_channel.is_disabled)
* }
* })
* }
*
* // ...
* }
*
* export default SalesChannel
*
* @customNamespace Hooks.Admin.Sales Channels
* @category Mutations
*/
export const useAdminUpdateSalesChannel = (
/**
* The sales channel's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminSalesChannelsRes>,
@@ -70,13 +128,42 @@ export const useAdminUpdateSalesChannel = (
}
/**
* Delete a sales channel
* @experimental This feature is under development and may change in the future.
* To use this feature please enable featureflag `sales_channels` in your medusa backend project.
* @param id
* @param options
* This hook deletes a sales channel. Associated products, stock locations, and other resources are not deleted.
*
* @example
* import React from "react"
* import { useAdminDeleteSalesChannel } from "medusa-react"
*
* type Props = {
* salesChannelId: string
* }
*
* const SalesChannel = ({ salesChannelId }: Props) => {
* const deleteSalesChannel = useAdminDeleteSalesChannel(
* salesChannelId
* )
* // ...
*
* const handleDelete = () => {
* deleteSalesChannel.mutate(void 0, {
* onSuccess: ({ id, object, deleted }) => {
* console.log(id)
* }
* })
* }
*
* // ...
* }
*
* export default SalesChannel
*
* @customNamespace Hooks.Admin.Sales Channels
* @category Mutations
*/
export const useAdminDeleteSalesChannel = (
/**
* The sales channel's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminSalesChannelsDeleteRes>,
@@ -97,14 +184,51 @@ export const useAdminDeleteSalesChannel = (
}
/**
* Remove products from a sales channel
* @experimental This feature is under development and may change in the future.
* To use this feature please enable featureflag `sales_channels` in your medusa backend project.
* @description remove products from a sales channel
* @param id
* @param options
* This hook removes a list of products from a sales channel. This doesn't delete the product. It only removes the
* association between the product and the sales channel.
*
* @example
* import React from "react"
* import {
* useAdminDeleteProductsFromSalesChannel,
* } from "medusa-react"
*
* type Props = {
* salesChannelId: string
* }
*
* const SalesChannel = ({ salesChannelId }: Props) => {
* const deleteProducts = useAdminDeleteProductsFromSalesChannel(
* salesChannelId
* )
* // ...
*
* const handleDeleteProducts = (productId: string) => {
* deleteProducts.mutate({
* product_ids: [
* {
* id: productId,
* },
* ],
* }, {
* onSuccess: ({ sales_channel }) => {
* console.log(sales_channel.id)
* }
* })
* }
*
* // ...
* }
*
* export default SalesChannel
*
* @customNamespace Hooks.Admin.Sales Channels
* @category Mutations
*/
export const useAdminDeleteProductsFromSalesChannel = (
/**
* The sales channel's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminSalesChannelsRes>,
@@ -131,14 +255,48 @@ export const useAdminDeleteProductsFromSalesChannel = (
}
/**
* Add products to a sales channel
* @experimental This feature is under development and may change in the future.
* To use this feature please enable featureflag `sales_channels` in your medusa backend project.
* @description Add products to a sales channel
* @param id
* @param options
* This hook adds a list of products to a sales channel.
*
* @example
* import React from "react"
* import { useAdminAddProductsToSalesChannel } from "medusa-react"
*
* type Props = {
* salesChannelId: string
* }
*
* const SalesChannel = ({ salesChannelId }: Props) => {
* const addProducts = useAdminAddProductsToSalesChannel(
* salesChannelId
* )
* // ...
*
* const handleAddProducts = (productId: string) => {
* addProducts.mutate({
* product_ids: [
* {
* id: productId,
* },
* ],
* }, {
* onSuccess: ({ sales_channel }) => {
* console.log(sales_channel.id)
* }
* })
* }
*
* // ...
* }
*
* export default SalesChannel
*
* @customNamespace Hooks.Admin.Sales Channels
* @category Mutations
*/
export const useAdminAddProductsToSalesChannel = (
/**
* The sales channel's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminSalesChannelsRes>,
@@ -165,18 +323,55 @@ export const useAdminAddProductsToSalesChannel = (
}
/**
* Add a location to a sales channel
* @experimental This feature is under development and may change in the future.
* To use this feature please install the stock location in your medusa backend project.
* @description Add a location to a sales channel
* @param options
* This hook associates a stock location with a sales channel. It requires the
* [@medusajs/stock-location](https://docs.medusajs.com/modules/multiwarehouse/install-modules#stock-location-module) module to be installed in
* your Medusa backend.
*
* @example
* import React from "react"
* import {
* useAdminAddLocationToSalesChannel
* } from "medusa-react"
*
* type Props = {
* salesChannelId: string
* }
*
* const SalesChannel = ({ salesChannelId }: Props) => {
* const addLocation = useAdminAddLocationToSalesChannel()
* // ...
*
* const handleAddLocation = (locationId: string) => {
* addLocation.mutate({
* sales_channel_id: salesChannelId,
* location_id: locationId
* }, {
* onSuccess: ({ sales_channel }) => {
* console.log(sales_channel.locations)
* }
* })
* }
*
* // ...
* }
*
* export default SalesChannel
*
* @customNamespace Hooks.Admin.Sales Channels
* @category Mutations
*/
export const useAdminAddLocationToSalesChannel = (
options?: UseMutationOptions<
Response<AdminSalesChannelsRes>,
Error,
{
/**
* The sales channel's ID.
*/
sales_channel_id: string
/**
* The location's ID.
*/
location_id: string
}
>
@@ -200,18 +395,56 @@ export const useAdminAddLocationToSalesChannel = (
}
/**
* Remove a location from a sales channel
* @experimental This feature is under development and may change in the future.
* To use this feature please install the stock location in your medusa backend project.
* @description Remove a location from a sales channel
* @param options
* This hook removes a stock location from a sales channel. This only removes the association between the stock
* location and the sales channel. It does not delete the stock location. This hook requires the
* [@medusajs/stock-location](https://docs.medusajs.com/modules/multiwarehouse/install-modules#stock-location-module) module to be installed in
* your Medusa backend.
*
* @example
* import React from "react"
* import {
* useAdminRemoveLocationFromSalesChannel
* } from "medusa-react"
*
* type Props = {
* salesChannelId: string
* }
*
* const SalesChannel = ({ salesChannelId }: Props) => {
* const removeLocation = useAdminRemoveLocationFromSalesChannel()
* // ...
*
* const handleRemoveLocation = (locationId: string) => {
* removeLocation.mutate({
* sales_channel_id: salesChannelId,
* location_id: locationId
* }, {
* onSuccess: ({ sales_channel }) => {
* console.log(sales_channel.locations)
* }
* })
* }
*
* // ...
* }
*
* export default SalesChannel
*
* @customNamespace Hooks.Admin.Sales Channels
* @category Mutations
*/
export const useAdminRemoveLocationFromSalesChannel = (
options?: UseMutationOptions<
Response<AdminSalesChannelsRes>,
Error,
{
/**
* The sales channel's ID.
*/
sales_channel_id: string
/**
* The location's ID.
*/
location_id: string
}
>
@@ -17,13 +17,40 @@ export const adminSalesChannelsKeys = queryKeysFactory(
type SalesChannelsQueryKeys = typeof adminSalesChannelsKeys
/** retrieve a sales channel
* @experimental This feature is under development and may change in the future.
* To use this feature please enable feature flag `sales_channels` in your medusa backend project.
* @description gets a sales channel
* @returns a medusa sales channel
/**
* This hook retrieves a sales channel's details.
*
* @example
* import React from "react"
* import { useAdminSalesChannel } from "medusa-react"
*
* type Props = {
* salesChannelId: string
* }
*
* const SalesChannel = ({ salesChannelId }: Props) => {
* const {
* sales_channel,
* isLoading,
* } = useAdminSalesChannel(salesChannelId)
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {sales_channel && <span>{sales_channel.name}</span>}
* </div>
* )
* }
*
* export default SalesChannel
*
* @customNamespace Hooks.Admin.Sales Channels
* @category Queries
*/
export const useAdminSalesChannel = (
/**
* The sales channel's ID.
*/
id: string,
options?: UseQueryOptionsWrapper<
Response<AdminSalesChannelsRes>,
@@ -41,13 +68,118 @@ export const useAdminSalesChannel = (
}
/**
* retrieve a list of sales channels
* @experimental This feature is under development and may change in the future.
* To use this feature please enable feature flag `sales_channels` in your medusa backend project.
* @description Retrieve a list of sales channel
* @returns a list of sales channel as well as the pagination properties
* This hook retrieves a list of sales channels. The sales channels can be filtered by fields such as `q` or `name`
* passed in the `query` parameter. The sales channels can also be sorted or paginated.
*
* @example
* To list sales channels:
*
* ```tsx
* import React from "react"
* import { useAdminSalesChannels } from "medusa-react"
*
* const SalesChannels = () => {
* const { sales_channels, isLoading } = useAdminSalesChannels()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {sales_channels && !sales_channels.length && (
* <span>No Sales Channels</span>
* )}
* {sales_channels && sales_channels.length > 0 && (
* <ul>
* {sales_channels.map((salesChannel) => (
* <li key={salesChannel.id}>{salesChannel.name}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default SalesChannels
* ```
*
* To specify relations that should be retrieved within the sales channels:
*
* ```tsx
* import React from "react"
* import { useAdminSalesChannels } from "medusa-react"
*
* const SalesChannels = () => {
* const {
* sales_channels,
* isLoading
* } = useAdminSalesChannels({
* expand: "locations"
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {sales_channels && !sales_channels.length && (
* <span>No Sales Channels</span>
* )}
* {sales_channels && sales_channels.length > 0 && (
* <ul>
* {sales_channels.map((salesChannel) => (
* <li key={salesChannel.id}>{salesChannel.name}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default SalesChannels
* ```
*
* By default, only the first `20` records are retrieved. You can control pagination by specifying the `limit` and `offset` properties:
*
* ```tsx
* import React from "react"
* import { useAdminSalesChannels } from "medusa-react"
*
* const SalesChannels = () => {
* const {
* sales_channels,
* limit,
* offset,
* isLoading
* } = useAdminSalesChannels({
* expand: "locations",
* limit: 10,
* offset: 0
* })
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {sales_channels && !sales_channels.length && (
* <span>No Sales Channels</span>
* )}
* {sales_channels && sales_channels.length > 0 && (
* <ul>
* {sales_channels.map((salesChannel) => (
* <li key={salesChannel.id}>{salesChannel.name}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default SalesChannels
* ```
*
* @customNamespace Hooks.Admin.Sales Channels
* @category Queries
*/
export const useAdminSalesChannels = (
/**
* Filters and pagination configurations applied on the retrieved sales channels.
*/
query?: AdminGetSalesChannelsParams,
options?: UseQueryOptionsWrapper<
Response<AdminSalesChannelsListRes>,
@@ -1,2 +1,17 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Shipping Option API Routes](https://docs.medusajs.com/api/admin#shipping-options).
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* A shipping option is used to define the available shipping methods during checkout or when creating a return.
* Admins can create an unlimited number of shipping options, each associated with a shipping profile and fulfillment provider, among other resources.
*
* Related Guide: [Shipping Option architecture](https://docs.medusajs.com/modules/carts-and-checkout/shipping#shipping-option).
*
* @customNamespace Hooks.Admin.Shipping Options
*/
export * from "./queries"
export * from "./mutations"
@@ -13,6 +13,50 @@ import { useMedusa } from "../../../contexts/medusa"
import { buildOptions } from "../../utils/buildOptions"
import { adminShippingOptionKeys } from "./queries"
/**
* This hook creates a shipping option.
*
* @example
* import React from "react"
* import { useAdminCreateShippingOption } from "medusa-react"
*
* type CreateShippingOption = {
* name: string
* provider_id: string
* data: Record<string, unknown>
* price_type: string
* amount: number
* }
*
* type Props = {
* regionId: string
* }
*
* const Region = ({ regionId }: Props) => {
* const createShippingOption = useAdminCreateShippingOption()
* // ...
*
* const handleCreate = (
* data: CreateShippingOption
* ) => {
* createShippingOption.mutate({
* ...data,
* region_id: regionId
* }, {
* onSuccess: ({ shipping_option }) => {
* console.log(shipping_option.id)
* }
* })
* }
*
* // ...
* }
*
* export default Region
*
* @customNamespace Hooks.Admin.Shipping Options
* @category Mutations
*/
export const useAdminCreateShippingOption = (
options?: UseMutationOptions<
Response<AdminShippingOptionsRes>,
@@ -30,7 +74,53 @@ export const useAdminCreateShippingOption = (
)
}
/**
* This hook updates a shipping option's details.
*
* @example
* import React from "react"
* import { useAdminUpdateShippingOption } from "medusa-react"
*
* type Props = {
* shippingOptionId: string
* }
*
* const ShippingOption = ({ shippingOptionId }: Props) => {
* const updateShippingOption = useAdminUpdateShippingOption(
* shippingOptionId
* )
* // ...
*
* const handleUpdate = (
* name: string,
* requirements: {
* id: string,
* type: string,
* amount: number
* }[]
* ) => {
* updateShippingOption.mutate({
* name,
* requirements
* }, {
* onSuccess: ({ shipping_option }) => {
* console.log(shipping_option.requirements)
* }
* })
* }
*
* // ...
* }
*
* export default ShippingOption
*
* @customNamespace Hooks.Admin.Shipping Options
* @category Mutations
*/
export const useAdminUpdateShippingOption = (
/**
* The shipping option's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminShippingOptionsRes>,
@@ -52,7 +142,43 @@ export const useAdminUpdateShippingOption = (
)
}
/**
* This hook deletes a shipping option. Once deleted, it can't be used when creating orders or returns.
*
* @example
* import React from "react"
* import { useAdminDeleteShippingOption } from "medusa-react"
*
* type Props = {
* shippingOptionId: string
* }
*
* const ShippingOption = ({ shippingOptionId }: Props) => {
* const deleteShippingOption = useAdminDeleteShippingOption(
* shippingOptionId
* )
* // ...
*
* const handleDelete = () => {
* deleteShippingOption.mutate(void 0, {
* onSuccess: ({ id, object, deleted }) => {
* console.log(id)
* }
* })
* }
*
* // ...
* }
*
* export default ShippingOption
*
* @customNamespace Hooks.Admin.Shipping Options
* @category Mutations
*/
export const useAdminDeleteShippingOption = (
/**
* The shipping option's ID.
*/
id: string,
options?: UseMutationOptions
) => {
@@ -17,7 +17,46 @@ export const adminShippingOptionKeys = queryKeysFactory(
type ShippingOptionQueryKeys = typeof adminShippingOptionKeys
/**
* This hook retrieves a list of shipping options. The shipping options can be filtered by fields such as `region_id`
* or `is_return` passed in the `query` parameter.
*
* @example
* import React from "react"
* import { useAdminShippingOptions } from "medusa-react"
*
* const ShippingOptions = () => {
* const {
* shipping_options,
* isLoading
* } = useAdminShippingOptions()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {shipping_options && !shipping_options.length && (
* <span>No Shipping Options</span>
* )}
* {shipping_options && shipping_options.length > 0 && (
* <ul>
* {shipping_options.map((option) => (
* <li key={option.id}>{option.name}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default ShippingOptions
*
* @customNamespace Hooks.Admin.Shipping Options
* @category Queries
*/
export const useAdminShippingOptions = (
/**
* Filters to apply on the retrieved shipping options.
*/
query?: AdminGetShippingOptionsParams,
options?: UseQueryOptionsWrapper<
Response<AdminShippingOptionsListRes>,
@@ -34,7 +73,42 @@ export const useAdminShippingOptions = (
return { ...data, ...rest } as const
}
/**
* This hook retrieves a shipping option's details.
*
* @example
* import React from "react"
* import { useAdminShippingOption } from "medusa-react"
*
* type Props = {
* shippingOptionId: string
* }
*
* const ShippingOption = ({ shippingOptionId }: Props) => {
* const {
* shipping_option,
* isLoading
* } = useAdminShippingOption(
* shippingOptionId
* )
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {shipping_option && <span>{shipping_option.name}</span>}
* </div>
* )
* }
*
* export default ShippingOption
*
* @customNamespace Hooks.Admin.Shipping Options
* @category Queries
*/
export const useAdminShippingOption = (
/**
* The shipping option's ID.
*/
id: string,
options?: UseQueryOptionsWrapper<
Response<AdminShippingOptionsRes>,
@@ -1,2 +1,17 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Shipping Profile API Routes](https://docs.medusajs.com/api/admin#shipping-profiles).
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* A shipping profile is used to group products that can be shipped in the same manner.
* They are created by the admin and they're not associated with a fulfillment provider.
*
* Related Guide: [Shipping Profile architecture](https://docs.medusajs.com/modules/carts-and-checkout/shipping#shipping-profile).
*
* @customNamespace Hooks.Admin.Shipping Profiles
*/
export * from "./queries"
export * from "./mutations"
@@ -1,5 +1,6 @@
import {
AdminDeleteShippingProfileRes,
AdminPostShippingProfilesProfileReq,
AdminPostShippingProfilesReq,
AdminShippingProfilesRes,
} from "@medusajs/medusa"
@@ -13,6 +14,40 @@ import { useMedusa } from "../../../contexts/medusa"
import { buildOptions } from "../../utils/buildOptions"
import { adminShippingProfileKeys } from "./queries"
/**
* This hook creates a shipping profile.
*
* @example
* import React from "react"
* import { ShippingProfileType } from "@medusajs/medusa"
* import { useAdminCreateShippingProfile } from "medusa-react"
*
* const CreateShippingProfile = () => {
* const createShippingProfile = useAdminCreateShippingProfile()
* // ...
*
* const handleCreate = (
* name: string,
* type: ShippingProfileType
* ) => {
* createShippingProfile.mutate({
* name,
* type
* }, {
* onSuccess: ({ shipping_profile }) => {
* console.log(shipping_profile.id)
* }
* })
* }
*
* // ...
* }
*
* export default CreateShippingProfile
*
* @customNamespace Hooks.Admin.Shipping Profiles
* @category Mutations
*/
export const useAdminCreateShippingProfile = (
options?: UseMutationOptions<
Response<AdminShippingProfilesRes>,
@@ -29,19 +64,62 @@ export const useAdminCreateShippingProfile = (
)
}
/**
* This hook updates a shipping profile's details.
*
* @example
* import React from "react"
* import { ShippingProfileType } from "@medusajs/medusa"
* import { useAdminUpdateShippingProfile } from "medusa-react"
*
* type Props = {
* shippingProfileId: string
* }
*
* const ShippingProfile = ({ shippingProfileId }: Props) => {
* const updateShippingProfile = useAdminUpdateShippingProfile(
* shippingProfileId
* )
* // ...
*
* const handleUpdate = (
* name: string,
* type: ShippingProfileType
* ) => {
* updateShippingProfile.mutate({
* name,
* type
* }, {
* onSuccess: ({ shipping_profile }) => {
* console.log(shipping_profile.name)
* }
* })
* }
*
* // ...
* }
*
* export default ShippingProfile
*
* @customNamespace Hooks.Admin.Shipping Profiles
* @category Mutations
*/
export const useAdminUpdateShippingProfile = (
/**
* The shipping profile's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminShippingProfilesRes>,
Error,
AdminPostShippingProfilesReq
AdminPostShippingProfilesProfileReq
>
) => {
const { client } = useMedusa()
const queryClient = useQueryClient()
return useMutation(
(payload: AdminPostShippingProfilesReq) =>
(payload: AdminPostShippingProfilesProfileReq) =>
client.admin.shippingProfiles.update(id, payload),
buildOptions(
queryClient,
@@ -51,7 +129,43 @@ export const useAdminUpdateShippingProfile = (
)
}
/**
* This hook deletes a shipping profile. Associated shipping options are deleted as well.
*
* @example
* import React from "react"
* import { useAdminDeleteShippingProfile } from "medusa-react"
*
* type Props = {
* shippingProfileId: string
* }
*
* const ShippingProfile = ({ shippingProfileId }: Props) => {
* const deleteShippingProfile = useAdminDeleteShippingProfile(
* shippingProfileId
* )
* // ...
*
* const handleDelete = () => {
* deleteShippingProfile.mutate(void 0, {
* onSuccess: ({ id, object, deleted }) => {
* console.log(id)
* }
* })
* }
*
* // ...
* }
*
* export default ShippingProfile
*
* @customNamespace Hooks.Admin.Shipping Profiles
* @category Mutations
*/
export const useAdminDeleteShippingProfile = (
/**
* The shipping profile's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminDeleteShippingProfileRes>,
@@ -16,6 +16,41 @@ export const adminShippingProfileKeys = queryKeysFactory(
type ShippingProfileQueryKeys = typeof adminShippingProfileKeys
/**
* This hook retrieves a list of shipping profiles.
*
* @example
* import React from "react"
* import { useAdminShippingProfiles } from "medusa-react"
*
* const ShippingProfiles = () => {
* const {
* shipping_profiles,
* isLoading
* } = useAdminShippingProfiles()
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {shipping_profiles && !shipping_profiles.length && (
* <span>No Shipping Profiles</span>
* )}
* {shipping_profiles && shipping_profiles.length > 0 && (
* <ul>
* {shipping_profiles.map((profile) => (
* <li key={profile.id}>{profile.name}</li>
* ))}
* </ul>
* )}
* </div>
* )
* }
*
* export default ShippingProfiles
*
* @customNamespace Hooks.Admin.Shipping Profiles
* @category Queries
*/
export const useAdminShippingProfiles = (
options?: UseQueryOptionsWrapper<
Response<AdminShippingProfilesListRes>,
@@ -32,7 +67,44 @@ export const useAdminShippingProfiles = (
return { ...data, ...rest } as const
}
/**
* This hook retrieves a shipping profile's details.
*
* @example
* import React from "react"
* import { useAdminShippingProfile } from "medusa-react"
*
* type Props = {
* shippingProfileId: string
* }
*
* const ShippingProfile = ({ shippingProfileId }: Props) => {
* const {
* shipping_profile,
* isLoading
* } = useAdminShippingProfile(
* shippingProfileId
* )
*
* return (
* <div>
* {isLoading && <span>Loading...</span>}
* {shipping_profile && (
* <span>{shipping_profile.name}</span>
* )}
* </div>
* )
* }
*
* export default ShippingProfile
*
* @customNamespace Hooks.Admin.Shipping Profiles
* @category Queries
*/
export const useAdminShippingProfile = (
/**
* The shipping option's ID.
*/
id: string,
options?: UseQueryOptionsWrapper<
Response<AdminShippingProfilesRes>,
@@ -1,2 +1,20 @@
/**
* @packageDocumentation
*
* Queries and Mutations listed here are used to send requests to the [Admin Stock Location API Routes](https://docs.medusajs.com/api/admin#stock-locations).
* To use these hooks, make sure to install the
* [@medusajs/stock-location](https://docs.medusajs.com/modules/multiwarehouse/install-modules#stock-location-module) module in your Medusa backend.
*
* All hooks listed require {@link Hooks.Admin.Auth.useAdminLogin | user authentication}.
*
* A stock location, provided by the [Stock Location module](https://docs.medusajs.com/modules/multiwarehouse/stock-location-module),
* indicates a physical address that stock-kept items, such as physical products, can be stored in.
* An admin can create and manage available stock locations.
*
* Related Guide: [How to manage stock locations](https://docs.medusajs.com/modules/multiwarehouse/admin/manage-stock-locations).
*
* @customNamespace Hooks.Admin.Stock Locations
*/
export * from "./queries"
export * from "./mutations"
@@ -1,4 +1,5 @@
import {
AdminPostStockLocationsLocationReq,
AdminPostStockLocationsReq,
AdminStockLocationsDeleteRes,
AdminStockLocationsRes,
@@ -15,6 +16,35 @@ import { adminProductKeys } from "../products"
import { adminVariantKeys } from "../variants"
import { adminStockLocationsKeys } from "./queries"
/**
* This hook creates a stock location.
*
* @example
* import React from "react"
* import { useAdminCreateStockLocation } from "medusa-react"
*
* const CreateStockLocation = () => {
* const createStockLocation = useAdminCreateStockLocation()
* // ...
*
* const handleCreate = (name: string) => {
* createStockLocation.mutate({
* name,
* }, {
* onSuccess: ({ stock_location }) => {
* console.log(stock_location.id)
* }
* })
* }
*
* // ...
* }
*
* export default CreateStockLocation
*
* @customNamespace Hooks.Admin.Stock Locations
* @category Mutations
*/
export const useAdminCreateStockLocation = (
options?: UseMutationOptions<
Response<AdminStockLocationsRes>,
@@ -32,19 +62,57 @@ export const useAdminCreateStockLocation = (
)
}
/**
* This hook updates a stock location's details.
*
* @example
* import React from "react"
* import { useAdminUpdateStockLocation } from "medusa-react"
*
* type Props = {
* stockLocationId: string
* }
*
* const StockLocation = ({ stockLocationId }: Props) => {
* const updateLocation = useAdminUpdateStockLocation(
* stockLocationId
* )
* // ...
*
* const handleUpdate = (
* name: string
* ) => {
* updateLocation.mutate({
* name
* }, {
* onSuccess: ({ stock_location }) => {
* console.log(stock_location.name)
* }
* })
* }
* }
*
* export default StockLocation
*
* @customNamespace Hooks.Admin.Stock Locations
* @category Mutations
*/
export const useAdminUpdateStockLocation = (
/**
* The stock location's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminStockLocationsRes>,
Error,
AdminPostStockLocationsReq
AdminPostStockLocationsLocationReq
>
) => {
const { client } = useMedusa()
const queryClient = useQueryClient()
return useMutation(
(payload: AdminPostStockLocationsReq) =>
(payload: AdminPostStockLocationsLocationReq) =>
client.admin.stockLocations.update(id, payload),
buildOptions(
queryClient,
@@ -54,7 +122,41 @@ export const useAdminUpdateStockLocation = (
)
}
/**
* This hook deletes a stock location.
*
* @example
* import React from "react"
* import { useAdminDeleteStockLocation } from "medusa-react"
*
* type Props = {
* stockLocationId: string
* }
*
* const StockLocation = ({ stockLocationId }: Props) => {
* const deleteLocation = useAdminDeleteStockLocation(
* stockLocationId
* )
* // ...
*
* const handleDelete = () => {
* deleteLocation.mutate(void 0, {
* onSuccess: ({ id, object, deleted }) => {
* console.log(id)
* }
* })
* }
* }
*
* export default StockLocation
*
* @customNamespace Hooks.Admin.Stock Locations
* @category Mutations
*/
export const useAdminDeleteStockLocation = (
/**
* The stock location's ID.
*/
id: string,
options?: UseMutationOptions<
Response<AdminStockLocationsDeleteRes>,
Loaded 100 of 2811 files, more files were not shown because too many files have changed in this diff. Show more