Recently, I have been working on a project in TypeScript where I need to fetch data from a URL and display it in my component. Transitioning from JavaScript to TypeScript has been a bit challenging for me. Here is the code snippet I have been working on:
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
interface ParamTypes {
id: string;
}
const SingleProductPage = () => {
const { id } = useParams<ParamTypes>();
const [data, setData] = useState();
const [isLoading, setIsLoading] = useState(false);
const fetchProduct = async () => {
setIsLoading(true);
const response = await fetch(
"myAPIEndpoint"
);
const responseJson = await response.json();
console.log(await responseJson.response);
setIsLoading(false);
setData(await responseJson.response);
};
useEffect(() => {
fetchProduct();
}, [id]);
if (isLoading) {
return <h1>Loading</h1>;
} else {
console.log(JSON.stringify(data.landingPageUrl));
return <h1>Loaded - {data.landingPageUrl}</h1>;
}
};
export default SingleProductPage;
Upon making an API call, the response follows this structure:
{
"response": {
"landingPageUrl": "https://google.com",
"name": "John",
"Job": {
"name": "google",
"designation": "s/w engg"
}
}
}
I am specifically interested in displaying the value of landingPageUrl
on my page. Additionally, I am looking to destructure the object. In JavaScript, we typically use const { name, id } = data;