Estoy tratando de obtener la lista de chats en mi aplicación usando react-query (useQuery). mi llamada API está en un componente diferente y estoy usando Axios para obtener los datos. pero el componente devuelve la función en sí, no los datos. ¿Qué parte es incorrecta?
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: [], }); }; }Le sugiero que refactorice un poco su código para solucionar algunos de sus problemas:
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(); // ... } Alternativamente, si desea usar getContacts como si fuera una función, simplemente no lo envuelva dentro de useQuery , ya que eso es lo que lo convierte en un gancho.
async function getUserData() { const data = await getContacts() // ... }