Request - Custom Hooks

mitchell_cheng

Mitchell

Posted on November 9, 2024

Request - Custom Hooks

You can find all the code in this post on the repo Github.


Request-related React custom hooks challenges


useSWR()

import { useState, useEffect } from "react";

function useSWR(_key, fetcher) {
  const [data, setData] = useState();
  const [error, setError] = useState();
  const fetchResult = fetcher();

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetchResult;
        setData(response);
      } catch (err) {
        setError(err);
      }
    };

    if (fetchResult instanceof Promise) {
      fetchData();
    }
  }, []);

  const result = fetchResult instanceof Promise ? data : fetchResult;

  return {
    data: result,
    error,
  };
}

/* Usage example */

export default function App() {
  return <div></div>;
}
Enter fullscreen mode Exit fullscreen mode

useFetch()

import { useState, useEffect } from "react";

function useFetch(url) {
  const [data, setData] = useState();
  const [error, setError] = useState();
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(url);
        if (!response.ok) {
          throw new Error(`HTTP error: ${response.status}`);
        }
        const result = await response.json();
        setData(result);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [url]);

  return { data, error, loading };
}

/* Usage example */

export default function App() {
  const { data, error } = useFetch("https://randomuser.me/api/");

  return (
    <div>
      <p>Fetch result: {JSON.stringify(data) ?? error}</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Reference

💖 💪 🙅 🚩
mitchell_cheng
Mitchell

Posted on November 9, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Request - Custom Hooks
webdev Request - Custom Hooks

November 9, 2024

React lifecycles - Custom Hooks
webdev React lifecycles - Custom Hooks

November 8, 2024

Event - Custom Hooks
webdev Event - Custom Hooks

November 7, 2024