Last active
January 1, 2026 14:02
-
-
Save Gaurav8757/479632dc3df6033f300fc27ba4b98764 to your computer and use it in GitHub Desktop.
useQuery from "@tanstack/react-query";
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 { useQuery } from "@tanstack/react-query"; | |
| import ApiServices from "../../apis/APIs.js"; | |
| // api has try, catch, finally | |
| class ApiServices { | |
| async getLandingPage(query = {}) { | |
| try { | |
| const response = await api.get(`/user/dashboard`, { | |
| params: query, | |
| }); | |
| return response?.data; | |
| } catch (error) { | |
| throw error.response?.data || error; | |
| } finally { | |
| console.log('Run in any condition') | |
| } | |
| } | |
| } | |
| // ## 1st Way => useQuery hook wise => here handle all global state update directly use it in component by global state. | |
| // 1. landing page Complete Version — Success === try API code, catch API code === Error, finaaly API code === Finally | |
| export const useLandingPage = (query = {}) => { | |
| return useQuery({ | |
| queryKey: ["landingpage", query], | |
| queryFn: async () => { | |
| const res = await ApiServices.getLandingPage(query); | |
| // If API returns success:false | |
| if (!res?.success) { | |
| throw new Error(res?.message || "Failed to load landing page"); | |
| } | |
| return res; | |
| }, | |
| // ⭐ SUCCESS | |
| onSuccess: (data) => { | |
| console.log("Landing Page API Success"); | |
| // yaha tum toast, UI update, state change sab kuch kar sakte ho | |
| // toast.success(data.message) | |
| }, | |
| // ❌ ERROR | |
| onError: (error) => { | |
| console.error("Landing Page API Error →", error?.message); | |
| // toast.error(error?.message || "Something went wrong"); | |
| }, | |
| // 🔥 FINALLY (Success ho ya Error — hamesha chalega) | |
| onSettled: () => { | |
| console.log("Landing Page: FINALLY block executed"); | |
| // yahan loader band karna, cleanup, etc. | |
| }, | |
| // ⚙ Config | |
| staleTime: 10 * 60 * 1000, | |
| cacheTime: 30 * 60 * 1000, | |
| refetchOnMount: false, | |
| refetchOnWindowFocus: false, | |
| refetchOnReconnect: false, | |
| retry: 1, | |
| }); | |
| }; | |
| // ## 2nd Way => useQuery handle in Component directly => here update all global state directly from component. | |
| export const useLandingPage = (query = {}) => { | |
| return useQuery({ | |
| queryKey: ["landingpage", query], | |
| queryFn: async () => await ApiServices.getLandingPage(query); | |
| staleTime: 10 * 60 * 1000, | |
| cacheTime: 30 * 60 * 1000, | |
| refetchOnMount: false, | |
| refetchOnWindowFocus: false, | |
| refetchOnReconnect: false, | |
| retry: 1 | |
| }); | |
| }; | |
| // Component | |
| import { useLandingPage } from "../hooks/useLandingPage"; | |
| import Loader from "../components/common/Loader"; | |
| import { toast } from "react-hot-toast"; | |
| export default function LandingPage() { | |
| // ⬅ query pass if needed | |
| const { data, error, isLoading, isError, isFetching } = useLandingPage(); | |
| // 1️⃣ Loading Phase | |
| if (isLoading || isFetching) return <Loader />; | |
| // 2️⃣ Error Phase (auto handled in hook, but UI also safe) | |
| if (isError) { | |
| return ( | |
| <div className="flex justify-center items-center h-screen"> | |
| <p className="text-red-600 font-medium text-lg"> | |
| {error?.message || "Something went wrong"} | |
| </p> | |
| </div> | |
| ); | |
| } | |
| // 3️⃣ Success Phase | |
| const landing = data?.data; // API response structure | |
| return ( | |
| <div className="p-4"> | |
| <h1 className="text-xl font-semibold text-gray-900"> | |
| Welcome {landing?.username} | |
| </h1> | |
| <p className="mt-2 text-gray-700"> | |
| {landing?.welcomeText || "Your dashboard is ready!"} | |
| </p> | |
| {/* Example UI */} | |
| <div className="mt-4 p-4 rounded-lg bg-gray-50 shadow"> | |
| <p>Total Orders: {landing?.totalOrders}</p> | |
| <p>Wallet Balance: ₹{landing?.wallet}</p> | |
| </div> | |
| </div> | |
| ); | |
| } | |
| // 2. Get logged in User data | |
| export const useGetLoginedUserInfo = () => { | |
| return useQuery({ | |
| queryKey: ["getLoginedUserInfo"], | |
| queryFn: ApiServices.getLoginedUserInfo, | |
| staleTime: 1000 * 60 * 5, // 5 minute | |
| cacheTime: 15 * 60 * 1000, // 15 minutes | |
| retry: false, // // avoid looping when token invalid or 401 | |
| suspense: true, // enables Suspense | |
| refetchOnMount: false, | |
| refetchOnWindowFocus: false, | |
| }); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment