Error: tanstack_react_query useQuery is not a function
Asked Answered
A

2

7

Error: (0 , tanstack_react_query__WEBPACK_IMPORTED_MODULE_3_.useQuery) is not a function

I am using next js and @tanstack/react-query for data fetching but getting the above error while fetching data.

The code I have done is given below.

Here is my component to fetch and render the data.

import React from 'react'
import ServiceProps from '../interfaces/ServiceProps'
import { fetchServices } from '../api/services/api'
import { useQuery } from "@tanstack/react-query";

const Service = ({ title, content }: ServiceProps) => {
    const { data, isLoading, isError, error, } = useQuery({ queryKey: ["fetchServices"], queryFn: fetchServices });
    console.log(data)
    return (

        <div className="dark:bg-transparent rounded-lg  dark:border-[#212425] dark:border-2 bg-blue-50 p-8">
            {/* <img alt="icon" srcset="/images/icons/icon-1.svg 1x, /images/icons/icon-1.svg 2x" src="/images/icons/icon-1.svg" width="40" height="40" decoding="async" data-nimg="1" className="w-10 h-10 object-contain block" loading="lazy" /> */}
            <div className="space-y-2 break-all">
                <h3 className="dark:text-white text-xl font-semibold">
                    {title}
                </h3>
                <p className=" leading-8 text-gray-lite dark:text-[#A6A6A6]">
                    {content}
                </p>
            </div>
        </div>


    )
}

export default Service

//Here is my API call using Axios

import axios from "axios";

export const fetchServices = async () => {
    const response = await axios.get(`api/services`);
    return response.data;
};
Artemisa answered 22/11, 2023 at 10:16 Comment(1)
I just added 'use client' to the component and it worked.Artemisa
H
21

You need use "use client"; at the top on Server page.

If you using SSR you can read more inside official doc`s Tanstack: https://tanstack.com/query/v4/docs/react/guides/ssr There are showing 2 versions of realisation. With Page or App Router.

Headwaters answered 8/12, 2023 at 10:25 Comment(4)
Yes, that is what I did.Artemisa
Note that by adding "use client"; you are switching to Client Component. Something one should be aware of. (for example, will not be good for SEO)Kaden
Also note that the guide (v5+ is here: tanstack.com/query/latest/docs/react/guides/ssr ) talks about Next.js Pages Router, not the newer App Router.Kaden
The guide for App Router is here: tanstack.com/query/latest/docs/react/guides/advanced-ssrKaden
F
2

The QueryClientProvider can only be used in client components , you can find the whole solution here: Using React Query with Next.js

Fabrizio answered 10/3 at 6:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.