Ionic + React - Custom Hook

In this page you will find the instructions to create a custom hook for your Ionic + React application. I will keep things very simple.

To start, lets start by creating an Ionic + React application. Open your terminal and send this command:

$ ionic start api_hook blank --type=react -capacitor --confirm --no-interactive
$ cd api_hook

I will be using VS Code, so open the project with VS Code:

$ code .

Add a file in the src/components/ directory. The file can be called useFetch.tsx and add the following code:

NOTICE: You will need axios for this example. to install is simple, just send this command: $ npm install axios

useFetch.tsx

import React, { useEffectuseState } from "react";
import axios from "axios";

function useFetch(urlany) {
  const [datasetData] = useState<any>(null);
  const [loadingsetLoading] = useState(false);
  const [errorsetError] = useState(null);
  useEffect(() => {
    setLoading(true); // set loading to true
    axios
      .get(url)
      .then((response=> {
        setData(response.data);
      })
      .catch((err=> {
        setError(err);
      })
      .finally(() => {
        setLoading(false);
      });
  }, [url]);

  // Function to call when button is clicked
  const refetch = () => {
    setLoading(true); // set loading to true
    axios
      .get(url)
      .then((response=> {
        setData(response.data);
      })
      .catch((err=> {
        setError(err);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  return { dataloadingerrorrefetch };
}

export default useFetch;


Now, open the src/components/exploreContainer.tsx file and make it look like this:

import "./ExploreContainer.css";

import useFetch from "../components/useFetch";

import {
  IonPage,
  IonHeader,
  IonToolbar,
  IonTitle,
  IonContent,
  IonCard,
  IonCardHeader,
  IonCardSubtitle,
  IonCardTitle,
  IonCardContent,
  IonButton,
from "@ionic/react";

const ExploreContainerReact.FC = () => {
  const { datarefetch } = useFetch("https://v2.jokeapi.dev/joke/any");

  if (!data) {
    return <h1>Loading...</h1>;
  } else {
    console.log(data);
    return (
      <IonPage>
        <IonHeader>
          <IonToolbar>
            <IonTitle>CardExamples</IonTitle>
          </IonToolbar>
        </IonHeader>
        <IonContent>
          <IonCard>
            <IonCardHeader>
              <IonCardSubtitle>Category: {data?.category}</IonCardSubtitle>
              <IonCardTitle>{data?.setup}</IonCardTitle>
            </IonCardHeader>

            <IonCardContent>{data?.delivery}</IonCardContent>
            <IonButton onClick={refetch}>Refresh</IonButton>
          </IonCard>

          <div className="container">
            <p>
              Ionic React Custom API Hook Example{" "}
              <a
                target="_blank"
                rel="noopener noreferrer"
                href="https://ionicframework.com/docs/components"
              >
                UI Components
              </a>
            </p>
          </div>
        </IonContent>
      </IonPage>
    );
  }
};

export default ExploreContainer;


That is all the code you will need. You can now start the ionic server to look at the application to make a call to the joke api.

$ ionic serve

Hope that helps.