TanStackT
TanStack16mo ago
1 reply
progressive-amaranth

How to enable a query for a specific query param

I have a GET endpoint, in which the values for the query params are passed in as arguments to the query, e.g.

function useGetItems(debouncedQuery: string, id?: string) {
  return useQuery({
    queryKey: ['items', { debouncedQuery, ...(id && { id }) }],
    queryFn: async () => {
      try {
        const response = await axios.get<Item[]>(`${ITEM_LOOKUP_ENDPOINT}/search`, {,
          params: {
            item: debouncedQuery,
            ...(id && { id }),
          },
        })

        if (id !== undefined) {
          return response.data
        }

        return response.data.filter(item => item.description.toLowerCase().includes(debouncedQuery.toLowerCase()))
      } catch (e) {
        throw new Error(e instanceof Error ? e.message : 'Item not found')
      }
    },
    enabled: () => {
      if (id !== undefined) {
        return !!id
      }

      return !!debouncedQuery
    },
  })
}


I only need to filter on the first query param, which is item , which will display an array of items which can be narrowed down further with the id query param.
Another API call would be required if the id query param has a value, which will then return an array of items, which can no longer be narrowed down.

An example would be, a user searches for console. The item query param will be console and in the response, you may find an object with a description property of "Nintendo - Switch, Wii U, Wii", and also has an id property. If the user selects this option, then the value id is passed into the id query param and a new list of items gets rendered. This time with the individual item.

I thought of using the refetch function, but it doesn't permit arguments being passed in.

What would be a good way to go about this?
Was this page helpful?