Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to configure a base url on react-query's QueryClient?

Well, I have this very simple file where I export a QueryClient from react-query library:

/queryClient.ts

import { QueryClient } from "react-query";

export const queryClient = new QueryClient();

Is there a way to set up a base url, or should I use something like context provider in order to do it?

like image 617
Andre GolFe Avatar asked Oct 26 '25 09:10

Andre GolFe


1 Answers

Well, as shown in this article:

React Query and TypeScript

And on the docs:

Default Query Function

You can configure a default query function:

export const queryClient = new QueryClient({
    defaultOptions: {
        queries: {
            queryFn: async ({ queryKey: [url] }) => {
                if (typeof url === 'string') {
                    const { data } = await axios.get(`${BASE_URL}/${url.toLowerCase()}`)
                    return data
                }
                throw new Error('Invalid QueryKey')
            },
        },
    },
});

Being able to call the UseQuery instance passing only the params of your api method call:

// You can even leave out the queryFn and just go straight into options
 function Post({ postId }) {
   const { status, data, error, isFetching } = useQuery(`/posts/${postId}`, {
     enabled: !!postId,
   })
 
   // ...
 }
like image 170
Andre GolFe Avatar answered Oct 28 '25 23:10

Andre GolFe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!