Passing a child component to an API component

Viewed 32

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;
2 Answers

You can use a higher-order component.

A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React’s compositional nature.

Example:

function withApiResponse(WrappedComponent, url, ...) {
 return function ApiFetcher(props) {
  ...
  const someData = ...;
  const items = ...;
  return (
      <div>
        <WrappedComponent someData/>
        <CompanyProfile items={items} />
      </div>
  );
 }
}

const Comments = withApiResponse(CommentsComponent, "/comments");
const Reviews = withApiResponse(ReviewsComponent, "/reviews");

function App() {
  return (
    <div>
      <Comments />
      <Reviews />
    </div>
  );
}

You can provide a function as the only child of the ApiFetcher and call it once the data is loaded:

<ApiFetcher url={apiUrl}>
  {(items) => {
    return <CompanyProfile items={items} />;
  }}
</ApiFetcher>

and then in ApiFetcher:

  if (error) {
    return <div>Error: {error.message}</div>;
  } else if (!isLoaded) {
    return <div>Loading...</div>;
  } else {
    // Call the provided function
    return props.children(items);
  }
Related