Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

useQuery doesn't return the data and the function is returned

I’m trying to get the list of the chats in my app using react-query(useQuery). my API call is in a different component and I’m using Axios to get the data. but the component is returning the function itself not the data .which part is Wrong?

import { useQuery } from "react-query";
import axios from "axios";

const getContacts = async () => {
  const headers = { Authorization: localStorage.getItem("token") };
  const options = {
    method: "GET",
    url: "http://127.0.0.1:8000/chat/mine/",
    headers: headers,
  };
  const { data } = await axios.request(options);

  return data;
};
function GetUserDataUseQuery() {
  return useQuery("getContacts", getContacts);
}
export default GetUserDataUseQuery;

function getUserData() {
  const data = GetUserDataUseQuery;

  return (dispatch) => {
    dispatch({
      type: GET_CONTACTS,
      payload: [],
    });
  };
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I suggest you refactor your code a little to fix some of your problems:

const getContacts = async () => { /*...*/ }
const useGetContacts = () {
  return useQuery('getContacts', getContacts)
}

// `useGetContacts` is a hook, so it should be called inside of a 
// component or another hook - you *cannot* call a hook inside of a 
// simple function, which is what you're attempting to do inside `getUserData`

function MyComponent() {
  const contacts = useGetContacts();
  // ...
}

Alternatively, if you do want to use getContacts as if it was a function, then simply don’t wrap it inside a useQuery, since that’s what turns it into a hook.

async function getUserData() {
  const data = await getContacts()
  // ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading