Data layer and data fetching in VTEX Sales App Extensibility
Learn how to use the data layer and data fetching for Sales App extensions.
This feature is in beta, and we're working to improve it. If you have any questions, please contact our Support.
When creating a Sales App extension, you may need to present data to the user, whether it's from the Sales App flow, VTEX APIs, or third-party APIs.
There are two ways for enabling your extensions to interact with data:
- Data layer resources, such as the
useCarthook oruseCartItem. - Data fetching from VTEX APIs or external APIs.
Data layer in extensions
All interactions with the Sales App data layer happen through functions and hooks provided by the @vtex/sales-app package.
Whenever possible, use the Sales App data layer, because this data is already cached in the core data layer. This approach prevents additional requests, enhancing application performance and benefiting your extensions.
For example, if you need to access cart item data while using the cart.cart-item.after extension point, you can use the useCartItem hook:
_10import { useCartItem } from '@vtex/sales-app'_10_10const MyComponent = () => {_10 const { item } = useCartItem()_10_10 return <p>Quantity: {item.quantity}</p>_10}
For detailed information about hooks and types for extensions, see the guide Sales App extensions hooks and types.
Data fetching in extensions
When you need to fetch data from VTEX APIs (for example, Intelligent Search) or external APIs, you can use the browser's Fetch API to make requests, as shown in the example below:
Extensions run in the browser, so authentication tokens and API keys included in requests can be exposed to users. The example below uses a public endpoint that does not require credentials. If your API requires authentication, create a VTEX IO app to proxy the request and handle authentication on the server.
_23import React, { useState, useEffect } from 'react';_23_23function MyCustomData() {_23 const [response, setResponse] = useState({ status: 'loading' });_23_23 useEffect(() => {_23 const fetchData = async () => {_23 try {_23 const response = await fetch('https://my-custom-data-api.com/custom-data');_23 const data = await response.json();_23 setResponse({ status: 'data', data });_23 } catch (error) {_23 setResponse({ status: 'error' })_23 }_23 };_23 fetchData();_23 }, []);_23_23 if (response.status === 'loading') return <MySkeleton />_23 if (response.status === 'error') return null_23_23 return <p>Data: {data.information}</p>_23}
When fetching data, handle loading states to ensure a better user experience. Additionally, allocate space in advance to avoid layout shift. Learn more in the guide Exploring Sales App extensions.