Home > front end >  No data returned from useQuery
No data returned from useQuery

Time:10-24

i am new to react query i did not get any data return by useQuery hook but api request is working fine

const listofgroupsapi = async (lastId, limit, id) => {
  const res = await axios.get(
    `${apiURL}/groups/getAllGroups?lastId=-1&limit=10&id=${id}`
  );
  console.log(res.data);
  return res.data;
};

const Superadminpanel = () => {
const [lastId, setLastId] = useState(0);
  const [limit, setLimit] = useState(10);
  const [id, setId] = useState(cookies.id);
  const { isLoading, data } = useQuery("groups", () => {
    listofgroupsapi(lastId, limit, id);
  });

  return (
    <div style={{ minHeight: "90vh" }}>
      <div>
        <h1>here we are</h1>
        {isLoading ? <h1>loading</h1> : <h1>not loading</h1>}
        {data ? <h1>data</h1> : <h1>no data:{data}</h1>}
      </div>
    </div>
  );
};

export default Superadminpanel;

console.log(res.data) gives me correct result from my api

response of my api

I don't know why useQuery doesn't give me any data

React query dev tool image

CodePudding user response:

Your main issue is that you aren't returning the promise result from listofgroupsapi() but there are also other improvements you can make.

As per the react-query documentation...

If your query function depends on a variable, include it in your query key

Since query keys uniquely describe the data they are fetching, they should include any variables you use in your query function that change

With that in mind, you should use the following

const listofgroupsapi = async (lastId, limit, id) =>
  (
    await axios.get(`/groups/getAllGroups`, { // no need for template literals
      baseURL: apiURL,
      params: { // query params are easier and safer this way
        lastId: -1, // not lastId?
        limit: 10, // not limit?
        id,
      },
    })
  ).data;

and in your component

const { isLoading, data } = useQuery(["groups", lastId, limit, id], () =>
  listofgroupsapi(lastId, limit, id) // no {...} means implicit return
);

CodePudding user response:

The issue could be that your useQuery api call is not returning anything, you either need to return a promise or the data so in your case updating as follows should work:

const { isLoading, data } = useQuery("groups", () => 
  listofgroupsapi(lastId, limit, id);
 );

Or you can return the data directly:

const { isLoading, data } = useQuery("groups", async() => 
  const data = await listofgroupsapi(lastId, limit, id);
  return data;
 );
  • Related