Last active
April 19, 2023 08:58
-
-
Save ercnshngit/5295a1f69c5de68a2c2da2b79f2d424b to your computer and use it in GitHub Desktop.
just a basic fetching snippet with abort controller
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 characters
| 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 |
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 characters
| 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 }; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment