Reputation: 497
How can I iterate through the promise object I have returned from my API call.
const [productData, setProductData] = useState(null)
useEffect(() => {
getProductdata()
}, [])
async function getProductdata(){
const secret = "SECRET"
const request = await fetch(`https://app.myapi.com/api/products/id`, {
headers: {
'Authorization': `Basic ${btoa(secret)}`,
'Accept': 'application/json'
}
}).then((request)=>{setProductData(request.json())})
}
console.log("pdata",productData)
Upvotes: 1
Views: 117
Reputation: 25398
If you're using Promise with then
then you should do as:
function getProductdata() {
const secret = "SECRET";
fetch(`https://app.myapi.com/api/products/id`, {
headers: {
Authorization: `Basic ${btoa(secret)}`,
Accept: "application/json",
},
})
.then((res) => res.json())
.then(data => setProductData(data);
}
console.log("pdata", productData);
Upvotes: 3
Reputation: 64657
Just await the promise before you call setProductData
:
const request = await fetch(`https://app.myapi.com/api/products/id`, {
headers: {
'Authorization': `Basic ${btoa(secret)}`,
'Accept': 'application/json'
}
})
const json = await request.json();
setProductData(json);
Upvotes: 1