5

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()?

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Could you explain best way to use it with they way my hook is constructed? Because now if I want to access query data I do: const { query } = useEvents(). How would I pass month here?
const { query} = useEvents(month) ?
@TkDodo what to do for scenerios where your is data not available already ? data is only made on event click and i need to call function that does a refetch with new data as parameter ?
same thing: you put that data into the query key and let react-query refetch automatically.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.