{"id":28092590,"url":"https://github.com/ordercloud-api/ordercloud-react-sdk","last_synced_at":"2025-05-13T13:21:20.999Z","repository":{"id":277212444,"uuid":"931699826","full_name":"ordercloud-api/ordercloud-react-sdk","owner":"ordercloud-api","description":"This React SDK provides a wrapper for the OrderCloud Javascript SDK in the form of a single provider and useful React hooks. It is used by the OC-Accelerator project for managing auth and generating dynamic tables and forms.","archived":false,"fork":false,"pushed_at":"2025-04-16T23:20:37.000Z","size":416,"stargazers_count":0,"open_issues_count":2,"forks_count":3,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-04-29T15:04:32.287Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ordercloud-api.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-02-12T17:58:00.000Z","updated_at":"2025-04-04T16:56:01.000Z","dependencies_parsed_at":"2025-02-12T18:55:20.565Z","dependency_job_id":"05ba466d-38f5-4f6e-a9f1-eb6c3c410d14","html_url":"https://github.com/ordercloud-api/ordercloud-react-sdk","commit_stats":null,"previous_names":["ordercloud-api/ordercloud-react-sdk"],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ordercloud-api%2Fordercloud-react-sdk","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ordercloud-api%2Fordercloud-react-sdk/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ordercloud-api%2Fordercloud-react-sdk/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ordercloud-api%2Fordercloud-react-sdk/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ordercloud-api","download_url":"https://codeload.github.com/ordercloud-api/ordercloud-react-sdk/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253948511,"owners_count":21988962,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-05-13T13:21:20.362Z","updated_at":"2025-05-13T13:21:20.986Z","avatar_url":"https://github.com/ordercloud-api.png","language":"TypeScript","readme":"# OrderCloud React\nThis is a developer library for OrderCloud developers utilizing React for their frontend development. It is essentially a wrapper for Tanstack query, which provides a lot of good functionality out of the box for background refreshes, request de-duplication, and caching. You configure your API client settings on the `OrderCloudProvider` which will provide you with a global context accessible though the `useOrderCloudContext()` hook. In addition to this context hook, it provides \"authenticated\" versions of `useQuery` and `useMutation` for reading and manipulating OrderCloud data in an efficient manner.\n\n# Peer Dependencies\nTo keep this package small, there are some required peer dependencies that are typical of an OrderCloud React application that utilizies tanstack libraries:\n\n- @tanstack/react-query@^5.20.1\n- @tanstack/react-table@^8.11.8\n- ordercloud-javascript-sdk@^5.3.0\n- react@^18.2.0\n- react-dom@^18.2.0\n\n# Usage\n\n## `OrderCloudProvider`\nIt is recommended that the `OrderCloudProvider` be configured as close to the root of your application as possible. At the very least it needs to wrap any part of your application that will need to communicate with the OrderCloud API.\n\n### Options\n\n#### **baseApiUrl**: `string`\nThe OrderCloud base API URL for your marketplace. Usually found in the OrderCloud Portal.\n\n#### **clientId**: `string`\nThe OrderCloud API Client ID that will be used for authentication\n\n#### **scope**: `string[]`\nAn array of OrderCloud API Roles that will be requested upon authentication\n\n#### **customScope**: `string[]`\nAn **optional** array of Custom Roles (strings) that will be requested upon authentication. Generally only needed if you are using Custom Roles in your marketplace's Security Profiles.\n\n#### **allowAnonymous**: `boolean`\nTrue will enable anonymous authentication (when the API client is properly configured). False will remain unauthenticated until the `login()` method is called by your application.\n\n#### **xpSchemas**: `OpenAPIV3.SchemaObject`\nAn **optional** [Open API specification](https://swagger.io/specification/) object containing one or more xp schema definitions for OrderCloud resources.  Xp schemas will be used to generate resource property definitions in the `useColumns` hook as well as form fields in the `useOcForm` hook.  In the absence of a provided resource schema, xp data types will be inferred by default for individual items when using the `useOcForm` hook.\n\n#### **defaultErrorHandler** `(error:OrderCloudError) =\u003e void`\nAn **optional** callback function for globally handling OrderCloud errors in your application. Useful for wiring up toast-like feedback.\n\n## `useOrderCloudContext()` hook\nThis hook returns the OrderCloud context that the OrderCloudProvider sets up based on your provided options. If anonymous authentication is allowed the OrderCloud context will automatically be in an authenticated state on first page load (shortly after the first React lifecycle).\n\n### Additional Properties\nThe OrderCloud context returns all of the information you configure on the OrderCloudProvider (`baseApiUrl`, `clientId`, etc.), along with some additional properties listed below.\n\n#### **isAuthenticated**: `boolean`\nWhen false, there is no valid OrderCloud access token available. Not to be confused with `isLoggedIn`.\n\n#### **isLoggedIn**: `boolean`\nWhen true, the currently active OrderCloud access token is a _registered_ user (not anonymous).\n\n#### **login**: `(username:string, password:string, rememberMe:boolean) =\u003e Promise\u003cAccessToken\u003e`\nAn asyncrhonous callback method for building a login form for your application. When **rememberMe** is set to `true`, the `OrderCloudProvider` will attempt to store and use the `refresh_token` as long as it is valid. It is not necessary to do anything with the `AccessToken` response as this method will take care of managing the active token and authentication state for you.\n\n#### **logout**: `() =\u003e void`\nA callback for logging out a registered user from your application. This will also clear the Tanstack query client cache for OrderCloud API calls, forcing any actively used queries to refetch once anonymous auth takes over again or the user logs back in.\n\n## `useAuthQuery()` hook\nThis is a wrapper for the `useQuery` Tanstack hook that utilizes the OrderCloud context to set `enabled` equal to `isAuthenticated`. It also checks for the presence of `query.error` and calls out to the supplied `defaultErrorHandler` if it was configured on the provider.\n\nThis hook supports all of the normal `UseQueryOptions` documented by Tanstack. In addition to these options, you can override the default error handler by passing a modified error handler as the second argument. Ultimately this hook will return the same `UseQueryResult` that is documented on Tanstack query.\n\n### Usage\nHere is an example of using the `useAuthQuery` hook to create a hook that returns the current user. \n```tsx\nimport { Me, MeUser, OrderCloudError, RequiredDeep } from \"ordercloud-javascript-sdk\";\nimport { useAuthQuery } from \"@rwatt451/ordercloud-react\";\nimport { UseMutationResult, UseQueryResult } from \"@tanstack/react-query\";\n\nexport function useCurrentUser():UseQueryResult\u003cRequiredDeep\u003cMeUser\u003e, OrderCloudError\u003e {\n  return useAuthQuery({\n    queryKey: [\"currentUser\"],\n    queryFn: async () =\u003e await Me.Get(),\n    retry: false,\n    refetchOnMount:false,\n  });\n}\n```\nSpecifying the `queryKey` is important here as it is what controls the query client caching and de-deuplication. This allows you to use the `useCurrentUser` hook anywhere in your application and it will only ever be called once.\n\n## `useAuthMutation()` hook\nThis is a wrapper for the `useMutation` Tanstack hook that utilizes the OrderCloud context to set `enabled` equal to `isAuthenticated` - just like `useAuthQuery`.\n\nThis hook supports all of the normal `UseMutationOptions` documented by Tanstack. Because `useMutation` already has an option for `onError`, the wrapped `useAuthMutation` will utilize the `defaultErrorHandler` if configured at the provider level and a more specific `onError` callback hasn't been provided. This ultimately returns the same `UseMutationRestult` as Tanstack query.\n\n### Usage\nHere is an example of using the `useAuthMutation` hook to create a `UseMutationResult` for modifying the current user. \n```tsx\nimport { Me, MeUser, OrderCloudError, RequiredDeep } from \"ordercloud-javascript-sdk\";\nimport { queryClient, useAuthMutation } from \"@rwatt451/ordercloud-react\";\nimport { UseMutationResult } from \"@tanstack/react-query\";\n\nexport function useMutateCurrentUser():UseMutationResult\u003cRequiredDeep\u003cMeUser\u003e, unknown, Partial\u003cMeUser\u003e, unknown\u003e {\n    return useAuthMutation({\n        mutationKey: [\"currentUser\"],\n        mutationFn: async (userData:Partial\u003cMeUser\u003e) =\u003e await Me.Patch(userData),\n        onSuccess: (data) =\u003e {\n            queryClient.setQueryData([\"currentUser\"], data)\n        },\n    })\n}\n```\nSpecifying the `mutationKey` is important here as it is what controls the query client caching and de-deuplication. The `onSuccess` option provides an avenue for updating the queryClient qury data cache. That way, any componenent that had used `useCurrentUser` will automatically get the updated value no matter where/when `mutate()` is called.\n\n## `useOcResourceList()` hook\nReturns an OrderCloud resource list query result from the resource List operation defined on the OrderCloud OpenAPI spec. This hook supports all of the normal `UseQueryOptions` documented by Tanstack. Ultimately this hook will return the same `UseQueryResult` that is documented on Tanstack query.\n\n### Options\n\n#### **resource**: `string`\nThe name of the OrderCloud resource to make a list call with.\n\n#### **listOptions**: `ServiceListOptions`\nAn **optional** listOptions object for the OrderCloud list call.\n\n#### **parameters**: `{ [key: string]: string }`\nAn **optional** parameters object for the OrderCloud list call.\n\n#### **queryOptions**: `UseQueryOptions`\nAn **optional** `UseQueryOptions` object.  It is recommended to use a `staleTime` value .\n\n### Usage\nHere is an example of using the `useOcResourceList` hook to create a `UseQueryResult` for modifying the current user. \n```tsx\nimport { useOcResourceList } from \"@rwatt451/ordercloud-react\";\n\n  const dataQuery = useOcResourceList('Orders', { IsSubmitted: true }, { direction: 'Incoming' }, {\n    staleTime: 300000, // 5 min\n  })\n```\n\n## `useOcResourceGet()` hook\nReturns an OrderCloud resource get query result from the resource Get operation defined on the OrderCloud OpenAPI spec. This hook supports all of the normal `UseQueryOptions` documented by Tanstack. Ultimately this hook will return the same `UseQueryResult` that is documented on Tanstack query.\n\n### Options\n\n#### **resource**: `string`\nThe name of the OrderCloud resource to make a get call with.\n\n#### **parameters**: `{ [key: string]: string }`\nAn **optional** parameters object for the OrderCloud get call.\n\n#### **queryOptions**: `UseQueryOptions`\nAn **optional** `UseQueryOptions` object.  It is recommended to use a `staleTime` value .\n\n### Usage\nHere is an example of using the `useOcResourceGet` hook to create a `UseQueryResult` for modifying the current user. \n```tsx\nimport { useOcResourceGet } from \"@rwatt451/ordercloud-react\";\n\n  const dataQuery = useOcResourceGet('Catalogs', { buyerID: 'BuyerA' }, {\n    staleTime: 'Infinity',\n  })\n```\n\n## `useMutateOcResource()` hook\nReturns an OrderCloud resource save or create query result from the resource Save or Create operation defined on the OrderCloud OpenAPI spec. This hook supports all of the normal `UseMutationOptions` documented by Tanstack. Ultimately this hook will return the same `UseMutationResult` that is documented on Tanstack query.\n\n### Options\n\n#### **resource**: `string`\nThe name of the OrderCloud resource to make a save or create call with.\n\n#### **parameters**: `{ [key: string]: string }`\nAn **optional** parameters object for the OrderCloud save or create call.\n\n#### **mutationOptions**: `UseMutationOptions`\nAn **optional** `UseMutationOptions` object. \n\n#### **isNew**: `boolean`\nAn **optional** boolean that indicates if an item is new.  If new, the Create operation will be used.\n\n### Usage\nHere is an example of using the `useMutateOcResource` hook to create a `UseMutationResult` for modifying the current user. \n```tsx\nimport { useMutateOcResource } from \"@rwatt451/ordercloud-react\";\nimport { useCallback } from \"react\";\n\n  const { mutateAsync: saveAsync } = useMutateOcResource('Products')\n  \n  const onSubmit = useCallback(\n    async (values: any) =\u003e {\n      await saveAsync(values.body);\n    },\n    [saveAsync]\n  );\n```\n\n## `useDeleteOcResource()` hook\nReturns an OrderCloud resource delete query result from the resource Delete operation defined on the OrderCloud OpenAPI spec. This hook supports all of the normal `UseMutationOptions` documented by Tanstack. Ultimately this hook will return the same `UseMutationResult` that is documented on Tanstack query.\n\n### Options\n\n#### **resource**: `string`\nThe name of the OrderCloud resource to make a delete call with.\n\n#### **parameters**: `{ [key: string]: string }`\nAn **optional** parameters object for the OrderCloud delete call.\n\n#### **mutationOptions**: `UseMutationOptions`\nAn **optional** `UseMutationOptions` object. \n\n### Usage\nHere is an example of using the `useDeleteOcResource` hook to create a `UseMutationResult` for modifying the current user. \n```tsx\nimport { useDeleteOcResource } from \"@rwatt451/ordercloud-react\";\nimport { useCallback } from \"react\";\n\n  const { mutateAsync: deleteAsync } = useDeleteOcResource('Orders', { direction: 'Outgoing' })\n  \n  const onDelete = useCallback(\n    async (values: any) =\u003e {\n      await deleteAsync();\n    },\n    [saveAsync]\n  );\n```\n\n## `useListAssignments()` hook\nReturns an OrderCloud resource delete query result from the resource Delete operation defined on the OrderCloud OpenAPI spec. This hook supports all of the normal `UseMutationOptions` documented by Tanstack. Ultimately this hook will return the same `UseMutationResult` that is documented on Tanstack query.\n\n### Options\n\n#### **resource**: `string`\nThe name of the OrderCloud resource to make a list call with.\n\n#### **operationInclusion**: `string`\nOptional string to be included in the resource operation name. ex. List{User}Assignments\n\n#### **listOptions**: `ServiceListOptions`\nAn **optional** listOptions object for the OrderCloud list call.\n\n#### **parameters**: `{ [key: string]: string }`\nAn **optional** parameters object for the OrderCloud list call.\n\n#### **queryOptions**: `UseQueryOptions`\nAn **optional** `UseQueryOptions` object.  It is recommended to use a `staleTime` value .\n\n### Usage\nHere is an example of using the `useListAssignments` hook to create a `UseQueryResult` for modifying the current user. \n```tsx\nimport { useOcResourceList } from \"@rwatt451/ordercloud-react\";\n\n  const dataQuery = useListAssignments('Catalogs', { ID: '100|101|102' }, {\n    staleTime: 300000, // 5 min\n  })\n```\n\n## `useMutateAssignment()` hook\nReturns an OrderCloud resource save assignment query result from the resource SaveAssignment operation defined on the OrderCloud OpenAPI spec. This hook supports all of the normal `UseMutationOptions` documented by Tanstack. Ultimately this hook will return the same `UseMutationResult` that is documented on Tanstack query.\n\n### Options\n\n#### **resource**: `string`\nThe name of the OrderCloud resource to make a list call with.\n\n#### **operationInclusion**: `string`\nOptional string to be included in the resource operation name. ex. Save{User}Assignments\n\n#### **parameters**: `{ [key: string]: string }`\nAn **optional** parameters object for the OrderCloud list call.\n\n#### **mutationOptions**: `UseMutationOptions`\nAn **optional** `UseMutationOptions` object. \n\n### Usage\nHere is an example of using the `useMutateAssignment` hook to create a `UseMutationResult` for modifying the current user. \n```tsx\nimport { useMutateAssignment } from \"@rwatt451/ordercloud-react\";\nimport { useCallback } from \"react\";\n\n  const { mutateAsync: saveAssignmentAsync } = useMutateAssignment('Categories', { catalogID: 'DefaultCatalog', categoryID: 'SoftGoods' })\n  \n  const onDelete = useCallback(\n    async (values: any) =\u003e {\n      await saveAssignmentAsync();\n    },\n    [saveAsync]\n  );\n```\n\n## `useDeleteAssignment()` hook\nReturns an OrderCloud resource assignment delete query result from the resource DeleteAssignment operation defined on the OrderCloud OpenAPI spec. This hook supports all of the normal `UseMutationOptions` documented by Tanstack. Ultimately this hook will return the same `UseMutationResult` that is documented on Tanstack query.\n\n### Options\n\n#### **resource**: `string`\nThe name of the OrderCloud resource to make a delete call with.\n\n#### **operationInclusion**: `string`\nOptional string to be included in the resource operation name. ex. Delete{User}Assignment\n\n#### **parameters**: `{ [key: string]: string }`\nAn **optional** parameters object for the OrderCloud delete call.\n\n#### **mutationOptions**: `UseMutationOptions`\nAn **optional** `UseMutationOptions` object. \n\n### Usage\nHere is an example of using the `useDeleteAssignment` hook to create a `UseMutationResult` for modifying the current user. \n```tsx\nimport { useDeleteAssignment } from \"@rwatt451/ordercloud-react\";\nimport { useCallback } from \"react\";\n\n  const { mutateAsync: deleteAsync } = useDeleteAssignment('Categories', { catalogID: 'DefaultCatalog', categoryID: 'SoftGoods' })\n  \n  const onDelete = useCallback(\n    async (values: any) =\u003e {\n      await deleteAsync();\n    },\n    [saveAsync]\n  );\n```\n\n## `useColumns()` hook\nThis hook utilizes the [Open API Spec](https://api.ordercloud.io/v1/openapi/v3) to generate properties, table headers, and `@tanstack/react-table` column groupings for a given OrderCloud resource. The dynamicColumns object returned from this hook are meant to be used as the `columns` option in `@tanstack/react-table`'s `useReactTable()` hook.  If a resource's xp schema is included in the `xpSchemas` option for `OrderCloudProvider`, these properties will be included in the resource's returned properties and column definitions. \n\n### Options\n\n#### **resourceId**: `string`\nThe OrderCloud resource name used for generating column information.\n\n#### **sortOrder**: `string[]`\nAn **optional** list that will be used to sort table header order if provided.\n\n#### **cellCallback**: `(info: CellContext\u003cunknown, unknown\u003e, properties: OpenAPIV3.SchemaObject, resourceId: string) =\u003e JSX.Element`\nAn **optional** callback for defining custom elements for `@tanstack/react-table` table cells by data type.\n\n## `useOcForm()` hook\nThis hook returns a `UseFormReturn` methods object and a \"shallowed\" resource schema. If a resource's xp schema is included in the `xpSchemas` option for `OrderCloudProvider`, these properties will be included in the form fields. \n\n### Options\n\n#### **resourceId**: `string`\nThe OrderCloud resource name used for generating column information.\n\n#### **initialValues**: `{ parameters?: {[key: string]: unknown}, body?: {[key: string]: unknown} }`\nAn **optional** object that contains initial parameter and body values for an item of a given resource ID.  The absence of body values indicates a new item.\n\n#### **props**: `UseFormProps`\nAn **optional** `react-hook-form` `useForm` props object \n\n## `useHasAccess()` hook\nThis hook determines whether a user has read or admin access to an OrderCloud resource by comparing the user's token and application scope to the OAuth roles indicated on the OpenAPI spec.\n\n### Options\n\n#### **resource**: `string`\nThe OrderCloud resource name used for generating column information.\n\n\n## Important Notes\nWhile it is not necessary to use the actual OrderCloud SDK to communicate with the OrderCloud API, it definitely makes things easier. The `isAuthenticated` state is based on the returned value of SDKs `Tokens.GetValidToken()` method and the OrderCloud SDK `Configuration` object is set up using the values passed into the `OrderCloudProvider`. Additonally, the SDK provides typed responses which make working with `useAuthQuery` and `useMutationQuery` generics easier.\n\nOn the flip side, it is also not entirely necessary to use the wrapped Tanstack hooks. If you want to just use the normal OrderCloud SDK, just be certain that you aren't making any calls when `isAuthenticated` is false. Though, in doing so you will miss out on all of the benefits that Tanstack provides.","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fordercloud-api%2Fordercloud-react-sdk","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fordercloud-api%2Fordercloud-react-sdk","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fordercloud-api%2Fordercloud-react-sdk/lists"}