I’m trying to pull postcode information and display it on my react app. The code so far looks as such:
const UKPar = () => {
postcode = "SW1A2AA"
const [ukPostcodeData, setUKPostcodeData] = useState({});
useEffect(() => {
fetch('https://api.postcodes.io/postcodes/' + postcode)
.then((res) => res.json())
.then((data) => {
console.log(data);
setUKPostcodeData(data);
})
.catch((err) => {
console.log(err.message);
});
}, [postcode]);
return(...)
}
export default UKPar;
This works fine and I can see that the data is displayed in the browser log as so:
{
"status": 200,
"result": {
"postcode": "SW1A 2AA",
"quality": 1,
"eastings": 530047,
"northings": 179951,
"country": "England",
"nhs_ha": "London",
"longitude": -0.127695,
"latitude": 51.50354,
"european_electoral_region": "London",
"primary_care_trust": "Westminster",
"region": "London",
"lsoa": "Westminster 018C",
"msoa": "Westminster 018",
"incode": "2AA",
"outcode": "SW1A",
"parliamentary_constituency": "Cities of London and Westminster",
"parliamentary_constituency_2024": "Cities of London and Westminster",
"admin_district": "Westminster",
"parish": "Westminster, unparished area",
"admin_county": null,
"date_of_introduction": "198001",
"admin_ward": "St James's",
"ced": null,
"ccg": "NHS North West London",
"nuts": "Westminster",
"pfa": "Metropolitan Police",
"codes": {
"admin_district": "E09000033",
"admin_county": "E99999999",
"admin_ward": "E05013806",
"parish": "E43000236",
"parliamentary_constituency": "E14000639",
"parliamentary_constituency_2024": "E14001172",
"ccg": "E38000256",
"ccg_id": "W2U3Z",
"ced": "E99999999",
"nuts": "TLI32",
"lsoa": "E01004736",
"msoa": "E02000977",
"lau2": "E09000033",
"pfa": "E23000001"
}
}
}
The issue is when I try and display this information the browser throws an error saying “ukPostcodeData.result is undefined”. I have have used the following code to try and display the information I need and other testing has shown that this should give me the correct result, however is causing errors when the HTML is rendered.
<td>{ukPostcodeData.result.parliamentary_constituency}</td>
I have tried using other methods to call the information needed from ukPostcodeData
to see if this would fix the problem. I used:
const getConstituency = () => {
return ukPostcodeData.result.parliamentary_constituency
}
...
return (
...
<td>{getConstituency()}</td>
...
)