Skip to content

Instantly share code, notes, and snippets.

@ercnshngit
Last active April 19, 2023 08:58
Show Gist options
  • Select an option

  • Save ercnshngit/5295a1f69c5de68a2c2da2b79f2d424b to your computer and use it in GitHub Desktop.

Select an option

Save ercnshngit/5295a1f69c5de68a2c2da2b79f2d424b to your computer and use it in GitHub Desktop.

Revisions

  1. ercnshngit revised this gist Apr 19, 2023. 1 changed file with 34 additions and 0 deletions.
    34 changes: 34 additions & 0 deletions useFetchWithSWR.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    import useSWR, { useSWRConfig } from "swr";
    import { BASE_URL } from "./utils";
    import { useRouter } from "next/router";

    export const fetchWithToken = async (url: string, token: string) => {
    const response = await fetch(url, {
    method: "GET",
    headers: {
    "Content-Type": "application/json",
    Accept: "application/json",
    crossorigin: "true",
    mode: "no-cors",
    Authorization: "Bearer " + token,
    },
    });
    const data = await response.json();
    if (!response.ok) {
    throw new Error(data.tr);
    }
    return data;
    };

    export const useFetch = (url: string, token: string | null) => {
    const router = useRouter();
    const { data, error, mutate, isLoading } = useSWR(
    [BASE_URL + url, token || ""],
    ([url, token]) => fetchWithToken(url, token)
    );
    if (error?.message === "Hesabınız aktif değil.") {
    router.push("/not-active");
    console.log("Hesabınız aktif değil.");
    }
    return { data, error, mutate, isLoading };
    };
  2. ercnshngit revised this gist Aug 27, 2022. No changes.
  3. ercnshngit created this gist Aug 25, 2022.
    44 changes: 44 additions & 0 deletions useFetch.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,44 @@
    import { useState, useEffect } from 'react'

    export const useFetch = (url) => {
    const [data, setData] = useState(null)
    const [isPending, setIsPending] = useState(false)
    const [error, setError] = useState(null)

    useEffect(() => {
    const controller = new AbortController()

    const fetchData = async () => {

    try {
    setIsPending(true)
    setData(null)
    const res = await fetch(url, { signal: controller.signal })
    if (!res.ok) throw new Error(res.statusText)
    const json = await res.json()
    setIsPending(false)
    setData(json)
    setError(null)
    } catch(err) {
    if (err.name === "AbortError") {
    console.log("fetch was aborted")
    } else {
    setIsPending(false)
    setError('Could not fetch the data')
    }
    }

    }

    fetchData()

    return () => {
    controller.abort()
    }

    }, [url])
    console.log(data)
    return { data, isPending, error }
    }

    export default useFetch