When the page load for the first time with API request it errors out. but after page load if I put the same code back it works fine. Can someone please help what am I missing here. Or show me the trick to delay the page loading until data loads from API.
import React, { useState, useEffect } from 'react'
export default function ProductPage({ data }) {
const [productData, setProductData] = useState(null)
useEffect(() => {
getProductdata()
}, [])
async function getProductdata(){
const secret = "SECRET"
const request = await fetch(`https://app.myapi.com/api/products/${data.productsCsv.id}`, {
headers: {
'Authorization': `Basic ${btoa(secret)}`,
'Accept': 'application/json'
}
}).then((request => request.json()))
.then(data => setProductData(data))
.catch(err=>console.log(err))
}
console.log("pdata",productData) // returns null on initial load and then it filled with data.
return (
<>
<div className="stock mb-4 ">
<p className="tracking-wider mb-2">Size</p>
{productData.variants.map((variant,index)=>{
<p>{variant.stock}</p>
if(variant.stock != 0){
return (
<button className={`p-2 border-gray-200 border mr-2 mb-2 hover:bg-black hover:text-white cursor-pointer focus:border-black ${activeSize === index ? 'bg-black text-white' : null}`} role="button" tabIndex={0}
onClick={() => {toggleSize(index); setSize(size)}}
onKeyDown={() => {toggleSize(index); setSize(size)}} key={index}>{variant.variation[0].option}-{variant.stock}</button>
)
}
else {
return(
<button className={`p-2 border-gray-200 border mr-2 mb-2 ${variant.stock == 0 ?'bg-gray-400 line-through text-red-500': null}`} disabled role="button" tabIndex={0}
onClick={() => {toggleSize(index); setSize(size)}}
onKeyDown={() => {toggleSize(index); setSize(size)}} key={index}>{variant.variation[0].option}-{variant.stock}</button>
)
}
})}
</div>
</>
)
productDatais initiallynulland will be on any subsequent renders until updated by the GET request. You are also console logging as an unintentional side-effect, so what you see actually logged shouldn't be a true measure of anything. What are you expecting to happen?