#Confused between older and newer usage of useQuery

8 messages · Page 1 of 1 (latest)

woeful shadow
#

I'm looking over some older code I wrote and it seems totally different to everything in the docs now.

export const useNextLaunch = () => {
    return useQuery<NextLaunch, Error>(queryKeys.nextLaunch, async ({ signal }) => {
        const response = await fetch(apiEndpoints.nextLaunch, { signal });
        const launch = camelCaseKeys(await response.json()) as NextLaunch;

        // return stuff
    });
};

Now when I look at the docs I see queryFn and queryKey everywhere and I don't understand why the API has changed this much? How would my old code look now?

useQuery({ queryKey: ['todos'], queryFn: fetchAllTodos })
useQuery({ queryKey: ['todos', todoId], queryFn: () => fetchTodoById(todoId) })
useQuery({
  queryKey: ['todos', todoId],
  queryFn: async () => {
    const data = await fetchTodoById(todoId)
    return data
  },
})
useQuery({
  queryKey: ['todos', todoId],
  queryFn: ({ queryKey }) => fetchTodoById(queryKey[1]),
})
inner zinc
#

this change is for the better.. instead of using positional arguments, the newer versions opt for options object instead

your code would look sth like this

useQuery({
  queryKey: queryKeys.nextLaunch,
  queryFn: async () => {
    // your queryFn here
  },
})
clever nexus
#

And please note that the object api has always existed all the way back since v3. We've used overloads to have one function that can be called with different number of arguments, but that has some other issues. The object api will become mandatory in v5, which is why we've changed the docs for v4 as well.

woeful shadow
#

OK thanks!

#

i had a look at the migration pages and didnt see this mentioned, if its not there maybe its worth adding

#

What about the generics though?

clever nexus
#

The generics have never been needed. The typescript docs have been updated a while back

woeful shadow
#

hmm, and how do we specify a return type then, just leave it to inference?