Last active
April 19, 2023 08:58
-
-
Save ercnshngit/5295a1f69c5de68a2c2da2b79f2d424b to your computer and use it in GitHub Desktop.
Revisions
-
ercnshngit revised this gist
Apr 19, 2023 . 1 changed file with 34 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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 }; }; -
ercnshngit revised this gist
Aug 27, 2022 . No changes.There are no files selected for viewing
-
ercnshngit created this gist
Aug 25, 2022 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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