Data-layer and data-fetching
When extending the UX/UI of Checkout, you may need to present data to the user, whether it’s data from the Checkout flow itself, additional information from VTEX APIs, or data from your own or third-party APIs.
In extension points, there are two main ways to interact with data:
- Data-layer resources, such as the
useCart
hook oruseCartItem
- Fetching data from VTEX APIs or external APIs
Data-layer
Whenever possible, prefer using the data-layer from the Checkout itself. This is recommended because these data are already cached within the core
Checkout’s data-layer, so accessing data (e.g., useCartItem
) won’t trigger additional requests, which is highly beneficial for both application
performance and your extensions.
All interactions with the Checkout data-layer happen through functions and hooks provided by the @vtex/checkout
package. 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:
import { useCartItem } from '@vtex/checkout'
const MyComponent = () => { const item = useCartItem()
return <p>Quantity: {item.quantity}</p>}
Data-fetching
The data in the Checkout layer might not always be sufficient for building your extension. Sometimes, you may need to communicate with a VTEX API (e.g., Intelligent Search) or even your own APIs or third-party APIs.
In these cases, you can simply use the browser’s Fetch API to make requests, just as you would in your everyday React applications:
import React, { useState, useEffect } from 'react';
function MyCustomData() { const [response, setResponse] = useState({ status: 'loading' });
useEffect(() => { const fetchData = async () => { try { const response = await fetch('https://my-custom-data-api.com/custom-data'); const data = await response.json(); setResponse({ status: 'data', data }); } catch (error) { setResponse({ status: 'error' }) } }; fetchData(); }, []);
if(response.status === 'loading') return <MySkeleton /> if(response.status === 'error') return null
return <p>Data: {data.information}</p>}