From 3aaa96a25ffb068c2770a48a14737c2bb7e76b99 Mon Sep 17 00:00:00 2001 From: Prince Muel Date: Fri, 12 May 2023 02:47:21 +0100 Subject: [PATCH] feat: add prefetch component Signed-off-by: Prince Muel --- src/lib/middleware/prefetch.tsx | 41 +++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/lib/middleware/prefetch.tsx diff --git a/src/lib/middleware/prefetch.tsx b/src/lib/middleware/prefetch.tsx new file mode 100644 index 0000000..b80d2fd --- /dev/null +++ b/src/lib/middleware/prefetch.tsx @@ -0,0 +1,41 @@ +import { useQueryClient } from '@tanstack/react-query'; +import { useCallback, useEffect } from 'react'; +import { Outlet } from 'react-router-dom'; +import { client } from '../client'; +import { useAuthDispatch } from '../context'; +import { useGetInvoicesQuery, useGetUserQuery } from '../hooks'; + +const Prefetch = () => { + const queryClient = useQueryClient(); + + const dispatch = useAuthDispatch(); + + const prefetchUser = useCallback(async () => { + await queryClient.prefetchQuery({ + queryKey: useGetUserQuery.getKey(), + queryFn: useGetUserQuery.fetcher(client), + }); + }, [queryClient]); + const prefetchInvoices = useCallback(async () => { + await queryClient.prefetchQuery({ + queryKey: useGetInvoicesQuery.getKey(), + queryFn: useGetInvoicesQuery.fetcher(client), + }); + }, [queryClient]); + + useEffect(() => { + async function init() { + await prefetchUser(); + + await prefetchInvoices(); + + dispatch('auth/addToken'); + dispatch('auth/addUser'); + } + + init(); + }, [prefetchInvoices, prefetchUser, dispatch]); + + return ; +}; +export default Prefetch;