DEV Community

Mitchell
Mitchell

Posted on

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

Top comments (0)