skip to Main Content

I have the following code.

import Post from "../post/Post";
import "./posts.scss";
import {useQuery} from "@tanstack/react-query";
import {makeRequest} from "../../axios";

//omitted code here

        const {isLoading, error, data } =  useQuery({
          queryKey: ["posts"],
          queryFn: () => {
           makeRequest.get("/posts").then((res) => {
            return res.data;
           })
          },
        });

In the browser I am getting the following error:
Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ["posts"]

2

Answers


  1. queryFn should return the promise.

    Login or Signup to reply.
  2. You cant really fix it as data can always be undefined because before the promise resolves, data will always be undefined.

    The only real way you can fix it is to give a default value to data

    const {isLoading, error, data = [] } =  useQuery({
        queryKey: ["posts"],
        queryFn: () => {
            makeRequest.get("/posts").then((res) => {
                return res.data;
            })
        },
    });
    

    Though this isn’t the best way to do it as data would always be an empty array, even if there is an error.

    What would probably be better is build out your component like this

    const Component = () => {
      const {isLoading, isError, data } =  useQuery({
        queryKey: ["posts"],
        queryFn: () => {
            makeRequest.get("/posts").then((res) => {
                return res.data;
            })
        },
      });
    
      if(isLoading) return <div>Loading...</div>
      if(isError || !data) return <div>Something went wrong</div>
    
      // data will now always be defined 
      return ...
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search