DEV Community

Mitchell
Mitchell

Posted on

1

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more