Question hunter
Question hunter

Reputation: 133

No data returned from useQuery

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

Upvotes: 0

Views: 1514

Answers (1)

Phil
Phil

Reputation: 164766

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
);

Upvotes: 1

Related Questions