Reputation: 65
I believe this is fairly straightforward but for some reason I'm not able to find the answers after quite abit of google :/
I have a simple component below that fetches some data from my spring boot app and converts it into a JSON promise.
I'm not sure if I am allowed to set the state using the promise, or do I have to parse it through another method before I do so? The state of visitDetails
remains empty after setVisitDetails
is called.
How do I use the map function to reference the variables that are in the response?
Component
import { useEffect, useState } from "react";
const QrCodeDisplay = () => {
const urlParams = new URLSearchParams(window.location.search);
const qrId = urlParams.get('qrCode');
const fetchQrURL = 'http://localhost:8080/api/qr-code/'+qrId;
const [visitDetails, setVisitDetails] = useState([]);
const fetchVisitURL = 'http://localhost:8080/api/visit-by-qrcodeid/'+qrId;
useEffect(()=> {
console.log(fetchVisitURL);
const fetchVisitDetail = async () => {
try{
const res = await fetch(fetchVisitURL,{
method: 'GET',
headers: {
'Content-type': 'application/json',
},
});
const jsonResponse = res.json();
console.log(jsonResponse);
setVisitDetails(jsonResponse);
}catch(error){
console.log("error", error);
}
};
fetchVisitDetail();
},[fetchVisitURL]);
return (
<div>
<h2>Your QR entry pass</h2>
<h3>Start Date of Visit:</h3>
<img src={fetchQrURL} alt="QR entry" width="200px" height="200px"></img>
</div>
)
}
export default QrCodeDisplay
JSON from backend (API works via Postman and React component returns promise as success)
[
{
"scheduledVisitId": 1,
"visitorId": 2,
"startDateOfVisit": "2021-01-18",
"endDateOfVisit": "2021-01-19",
"qrCodeId": "c4ca4238a0b923820dcc509a6f75849b",
"valid": true,
"oneTimeUse": false,
"raisedBy": 123456
}
]
Upvotes: 0
Views: 53
Reputation: 2586
You missed await before res.json()
useEffect(()=> {
console.log(fetchVisitURL);
const fetchVisitDetail = async () => {
try{
const res = await fetch(fetchVisitURL,{
method: 'GET',
headers: {
'Content-type': 'application/json',
},
});
const jsonResponse = await res.json();
console.log(jsonResponse);
setVisitDetails(jsonResponse);
}catch(error){
console.log("error", error);
}
};
fetchVisitDetail();
},[fetchVisitURL]);
```
Upvotes: 1