I'm trying to implement an API fetcher as a reusable component in order to reduce duplicate code.
How do I pass a child component to this ApiFetcher so that it renders the specific child instead of a hard coded component?
Besides, is my CompanyProfile component coded in an effective way or is there room for optimisation?
import React from "react";
import { useState, useEffect } from "react";
function ApiFetcher(props) {
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [items, setItems] = useState([]);
useEffect(() => {
fetch(props.url)
.then((res) => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result);
},
(error) => {
setIsLoaded(true);
setError(error);
}
);
}, []);
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
// TODO: return props.childrend instead of hard coded component
return (
<div>
<CompanyProfile items={items} />
</div>
);
}
}
function CompanyProfile(props) {
return (
<div>
<ul>
{props.items.map((item) => (
<li key={item.symbol}>
{item.companyName} {item.price}
</li>
))}
</ul>
</div>
);
}
function App() {
const apiUrl =
"https://financialmodelingprep.com/api/v3/profile/AAPL?apikey=demo";
// TODO: implement children of ApiFetcher
return (
<div>
<ApiFetcher url={apiUrl}>
</ApiFetcher>
</div>
);
}
export default App;