I'm trying to find an object in an array and return that specific object. I'm new to typescript, so I tried to solve it this way and I'm not sure why it's not working.
Edited: My code is not even being complied! I'm getting the error below:
TypeScript error in /Users/.../api/VaccineDataApi.tsx(64,14): Object is possibly 'undefined'. TS2532
import React, { useEffect, useState } from 'react';
import axios from 'axios';
type VaccineDataState = {
Date: Date,
Location: string, //Location is state Abbreviations like 'WA'
LongName: string,
Doses_Distributed: number,
}
const VaccineData = () => {
const [vaccine, SetVaccine] = useState<VaccineDataState[]>([])
const [errorMessage,SetErrorMessage] = useState(null)
useEffect(() => {
axios.get("https://localhost:3000")
.then((response) => {
const apiVaccineData = response.data.vaccination_data;
SetVaccine(apiVaccineData);
})
.catch((error) => {
SetErrorMessage(error.message);
console.log(errorMessage);
})
}, []);
let vaccineData = vaccine.find(state => state.Location === 'WA');
return(
<div>
<p>test</p>
{vaccineData.Location}
</div>
)
};
export default VaccineData;
VaccineData
refers to the functional component. You probably wanted vaccineData.Location
instead of VaccineData.Location
.
Edit: To fix let vaccineData: VaccineDataState | undefined Object is possibly 'undefined'
, you could:
Add !
to tell the Typescript compiler that vaccineData
will never be undefined
(only if you are sure that it never actually is):
let vaccineData = vaccine.find(state => state.Location === 'WA')!;
or
Add some code to check for undefined
:
let vaccineData = vaccine.find(state => state.Location === 'WA');
if(!vaccineData)
return <p>Data not found!</p>;
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments