FD3
FD3

Reputation: 1946

Next.js: How to create get request using React Query

I want to integrate to React query for fetching the data from server.
So far I've been fetching the rest api via Axios.
I have created a custom hook for fetching and want to transform and implement with react query. While trying to implement the same logic I encountered an error trying to destructure the fetched data const { data } = useApiRequest(headersUrl):

error - TypeError: (0 , _hooks_useApiRequest__WEBPACK_IMPORTED_MODULE_1__.UseApiRequest) is not a function

Here is the old logic for fetching

import * as React from "react";
import { useState, useEffect } from "react";
import axios from "axios";
import { HeaderToken } from "../services/api";
export const useApiRequest = (url: any) => {
 const [data, setData] = useState<[] | any>([]);

 useEffect(() => {
   const fetchData = () => {
     axios
       .get(url, {
         headers: {
           Authorization: `Basic ${HeaderToken}`,
         },
       })
       .then((response) => {
         setData(response.data);
       })
       .catch((error) => console.error(error));
   };
   fetchData();
 }, [url]);

 return { data };
};

And here is how I'm trying to convert it:

import { HeaderToken } from "../services/api";
import { useQuery } from "react-query";

export const useApiRequest = (url: any) => {
  const { isLoading, data } = useQuery("bc", async () => {
    const response = await fetch(url, {
      method: "get",
      headers: {
        Authorization: `Basic ${HeaderToken}`,
        "Content-Type": "application/json",
      },
    });
    if (!response.ok) throw new Error(response.statusText);
    return await response.json();
  });

  return { data };
};

Upvotes: 0

Views: 1484

Answers (1)

Ahmed Hany
Ahmed Hany

Reputation: 1040

I can't see the problem, actually, I tried the same code you shared with a local API I have and it's working

The Hook

import { useQuery } from 'react-query'

export const clientAPI = (url) => {
    const { isLoading, data } = useQuery("bc", async () => {
        const response = await fetch(url, {
            method: "get"
        });
        if (!response.ok) throw new Error(response.statusText);
        return await response.json();
    });
    return { data };
};

React Component

import * as React from "react";
import { clientAPI } from "../hooks/clientAPI";

export default function Home() {

  const { data } = clientAPI('http://localhost:5000/')

  return (
    <div>
      {JSON.stringify(data)}
    </div>
  )
}

_app.js

import { QueryClient, QueryClientProvider, useQuery } from 'react-query'
const queryClient = new QueryClient()

function MyApp({ Component, pageProps }) {
  return (<QueryClientProvider client={queryClient}>
    <Component {...pageProps} />
  </QueryClientProvider>)
}

export default MyApp

I'm using [email protected], [email protected]

what are the versions you are using?

Upvotes: 2

Related Questions