Data fetching issues?

Hi guys, doing a small e-commerce app, wanted to output the total number of products, the expected result is 12, but on output I got 2, which confused me. I checked on the test page via console.log and the total number of products is 12, I still can't figure out what is wrong First pic is length 2 for some reason (12 is expected) Second pic shows the code I ran to test The third pic is the output
No description
No description
No description
3 Replies
Joao
Joao10mo ago
All you are doing is logging the result to the console, which appears as 12 items. Seems to be working fine.
⛧
OP10mo ago
First Snippet:
const handleGetAllProducts = async () => {
try {
const response = await fetch('/api/products', {
method: 'GET',
})
if (response.ok) {
const data = await response.json()
console.log('All products:', data)
} else {
console.error('Failed to get all products')
}
} catch (error) {
console.error('Error getting all products:', error)
}
}
const handleGetAllProducts = async () => {
try {
const response = await fetch('/api/products', {
method: 'GET',
})
if (response.ok) {
const data = await response.json()
console.log('All products:', data)
} else {
console.error('Failed to get all products')
}
} catch (error) {
console.error('Error getting all products:', error)
}
}
Second Snippet:
import products from '../../pages/api/products'

<div className={styles.productsNumber}>{products.length}</div>
import products from '../../pages/api/products'

<div className={styles.productsNumber}>{products.length}</div>
I think I left out details because I wanted to sleep. Though the snippets are not equal, but they should show the total number there and there. I was wondering why there is a discrepancy in the total numbers. Seems after a nap I can think of why it works that way. Items should have been loaded asynchronously, and useState should be used to make sure the correct quantity of items is displayed. My bad for being not that informative at night
Joao
Joao10mo ago
Yeah it looks like it's a presentation layer issue, just passing data around from one file to another. Based on the screenshots it all looked fine to me. When in doubt take a break and come back to it later, it usually works 🙂
Want results from more Discord servers?
Add your server