React Intermediate Part 2 - Fetching Data

I think to be following religiously the course material, but I am getting two errors in the below TodoList.tsx file that has me blocked. I thank you in advance for your help.

Error 1 on line 18: queryKey: [“todos”],
The error is:
No overload matches this call.
The last overload gave the following error.
Argument of type ‘{ queryKey: string[]; queryFn: () => () => Promise<Todo[]>; }’ is not assignable to parameter of type ‘QueryKey’.
Object literal may only specify known properties, and ‘queryKey’ does not exist in type ‘readonly unknown[]’.ts(2769)
useQuery.d.ts(16, 25): The last overload is declared here.

Error 2 on line 26: {todos?.map((todo) => (
The error is:
Property ‘map’ does not exist on type ‘NonNullable’.

import { useQuery } from "@tanstack/react-query";
import axios from "axios";

interface Todo {
    id: number;
    title: string;
    userId: number;
    completed: boolean;
}

const TodoList = () => {
    const fetchTodos = () =>
        axios
            .get<Todo[]>("https://jsonplaceholder.typicode.com/todos")
            .then((res) => res.data);

    const { data: todos, error } = useQuery<Todo[], Error>({
        queryKey: ["todos"],
        queryFn: () => fetchTodos,
    });

    if (error) return <p>{error.message}</p>;

    return (
        <ul className="list-group">
            {todos?.map((todo) => (
                <li key={todo.id} className="list-group-item">
                    {todo.title}
                </li>
            ))}
        </ul>
    );
};

export default TodoList;

Started the course this morning and got the exact same error. :crossed_fingers: Hopefully someone has a solution for this.

So I found the problem in the code…you have to remove the arrow function from the queryFn - like below:

const { data: todos, error } = useQuery<Todo[], Error>({
        queryKey: ["todos"],
        queryFn: fetchTodos,
    });

Mine is working now… Hope this helps.

Checkout the docs on tanstack regarding useQuery: Queries | TanStack Query Docs

1 Like

Thank you, it works! :tada: It is now perfectly clear why the error was happening. This happens sometimes when studying late at night.

Happens to me all the time. I find using difchecker very helpful: https://www.diffchecker.com/