I fetch data from API and I want to pass it in HotelCard component as props.
export default function HotelPage() {
const [hotelInfo, setHotelInfo] = useState<object | null>(null);
const params = useParams();
const id = params.id;
async function fetchHotelById() {
const result = await HotelsService.fetchById(id);
setHotelInfo({
name: result.name,
description: result.summary.tagline,
location: {
address: result.addressLine,
city: result.city,
countryCode: result.countryCode
},
images: result.images,
review: result.reviewInfo.value
});
}
useEffect(() => {
fetchHotelById();
}, [id])
return (
<>
<HotelCard info={hotelInfo}/> //here info is underlined
</>
)
}
The issue with info:
Type ‘{ info: object | null; }’ is not assignable to type
‘IntrinsicAttributes & hotelInfoProps’. Property ‘info’ does not
exist on type ‘IntrinsicAttributes & hotelInfoProps’.
HotelCard.tsx
export default function HotelCard({ info }: hotelInfoProps) {
return (
<section className='hotel__card'>{info.name}</section>
)
}
The issue is:
Property ‘info’ does not exist on type ‘hotelInfoProps’
And hotelInfoProps:
export type hotelInfoProps = {
name: string;
description: string;
location: {
address: string;
city: string;
countryCode: string;
};
images: object [];
review: string;
}
I cannot figure out how to solve this issue with info and what causes the problem.
3
Answers
Thanks for all your answers and help, it really helped me a lot. What worked for me was adding additional type:
and:
You are passing the
hotelInfoProps
incorrectly, because you are not using the proper syntax for typing props in React. You can try this:You can try this:
But it is not the recommended way to type props in React. You should use the
React.FC
(orReact.FunctionComponent
) type to declare your functional component, and pass the props type as a generic parameter. For example:Your object hotelInfo is initialized as null before fetching the data from you API but you pass this object to your HotelCard component that expects to have a non nullable object. You should either put a condition to render the component only if hotelInfo is not null or update HotelCard to also handle a null object.