In a marketplace project, I want to show product information and store information like "more products from this store".
Currently my code does the following:
- Get the product ID from URL and make an API call using that ID to get the product information.
- State variable
product
is updated with that product information. - The product object includes a
storeName
value which I try to use to make another API call to get the store information (more products from that store)
The last step doesn't work. The site loads and the product information is displayed correctly, however the JSON response from the store API call shows an error because the storeName
value is null. The store information is not displayed.
Code:
function ProductPage() {
const { productUrl } = useParams();
const [product, setProduct] = useState([]);
const [store, setStore] = useState([]);
const {
name,
price,
description,
images,
storeName
} = product;
useEffect(() => {
getProduct();
getStore();
}, []);
const getProduct = async () => {
const product = await API.graphql(
graphqlOperation(queries.productByProductId, {
productId: productUrl,
})
);
setProduct(product.data.productByProductId.items[0]);
};
const getStore = async () => {
const store = await API.graphql(
graphqlOperation(queries.storeByName, {
name: storeName,
})
);
setStore(store.data.storeByName.items[0]);
};