'How to fetch with parameters using React Query?

For the sake of this question let's first assume existence of such entity:

export interface Event {
    id: number;
    date: Date;
}

Then let's assume there's backend with such endpoints:

GET /events -> returns all events
GET /events?startDate=dateA&endDate=dateB -> returns all events between dateA and dateB

I create hook containing 4 methods (one for each CRUD operation) in my frontend code like this:

export function useEvents() {
    const getEvents() = async () => {
        const response = await axios.get(`events`);
        return response.data;
    }
    const postEvent()...
    const updateEvent()...
    const deleteEvent()...

    const query = useQuery('events', getEvents);
    const postMutation = ...
    const updateMutation = ...
    const deleteMutation = ...

    return { query, postMutation, updateMutation, deleteMutation }
}

This architecture works like a charm but I got to the point where I would like to conditionaly fetch events based on currently chosen month in my Calendar.tsx component.

How would I inject this information into useQuery() and getEvents()?



Solution 1:[1]

the query key should contain all "dependencies" that you need for your fetch. This is documented in the official docs here, and I've also blogged about it here.

So, in short:

const getEvents(month) = async () => {
  const response = await axios.get(`events/${month}`);
  return response.data;
}

const query = useQuery(['events', month], () => getEvents(month));

The good thing is that react-query will always refetch when the key changes, so data for every month is cached separately, and if the month changes, you'll get a fetch with that month.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TkDodo