Description
A collection of React hooks that interface with the Salesforce REST API.
Usage
Salesforce Authentication
sfdc-react-hooks provides no mechanism for authentication. It is up to you to handle authentication and provide an Authorization token to sfdc-react-hooks.
ForceProvider
All components that make use of the provided hooks must be direct or indirect descendents of a <ForceProvider>
. <ForceProvider>
accepts a config property to specify the Salesforce instanceUrl, apiVersion (defaults to 47.0), and authToken.
Hooks
All hooks return an object with data, loading, and error properties. data contains the returned data from Salesforce in a format specific to the hook, loading is a boolean that states whether the REST transaction is still in progress, and error is either a collection of errors returned from Salesforce, or a non-Salesforce error thrown during the REST call.
useDescribe(sObjectType)
Gets the metadata for the requested SObject type and stores it in data.
useSOQL(query, variables)
Executes a SOQL query and returns the results in data.records.
useSOSL(searchString, variables)
Executes a SOSL search and returns the results in data.searchRecords.
useSOQL and useSOSL Variables
Dynamic variables can be specified for queries and searches, similar to how they are handled in Apex. Presently, the only supported variable types are strings, numbers, and lists (of strings or numbers);
Variables Example
const QUERY_CONTACTS_IN_LIST = ` SELECT Id, Name FROM Contact WHERE Id IN :contactIds`; ... const queryVariables setQueryVariables = ;const data loading error = ;
Examples
ForceProvider Example
;;;;; const config = instanceUrl: 'https://yourdomain.my.salesforce.com' apiVersion: 45 // default is 47 authToken: '*your token here*' // token only, omit "Bearer "; const App = { return <ForceProvider config=config> <QueryExample /> <SearchExample /> <DescribeExample /> </ForceProvider> }; ;
useSOQL( ) Example
;; // get up to 10 Jimsconst TEN_JIMS = ` SELECT Id, Name FROM Contact WHERE (Name LIKE 'Jim%') LIMIT 10`; const QueryExample = { const data loading error = ; ifdata return <ul> datarecords </ul> ; ifloading // handle loading state here iferror // handle error here }; ;
useSOSL( ) Example
;; // find some Jims in Accounts and Contactsconst SEARCH_ACCOUNTS_CONTACTS = ` FIND {Jim*} IN NAME FIELDS RETURNING Contact(Id, Name), Account(Id, Name)`; const SearchExample = { const data loading error = ; ifdata return <ul> datasearchRecords; ifloading // handle loading state here iferror // handle error here }; ;
useDescribe( ) Example
;; const DescribeExample = { const data loading error = ; ifdata return <div> <ul> datafields </ul> </div> ; ifloading // handle loading state here iferror // handle error here }; ;