Home > front end >  useQuery doesn't return the data and the function is returned
useQuery doesn't return the data and the function is returned

Time:12-31

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: [],
    });
  };
}

CodePudding user response:

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()
  // ...
}
  • Related