TanStackT
TanStack3y ago
5 replies
faint-white

useQuery refetch

Hello everyone, I have a react native with typescript using zustand and react-query latest version.

I have a question that I have zustand store to keep my filters object, if it changes, I want to make the
useQuery
to get the latest data with the filters.

Here's the code:

zustand store:
const usePlansStore = create<Timeline>((set, get) => ({
  filters: {
    date_range: "this_year",
  },

  getFilters: () => {
    const state = get();
    return state.filters;
  },

  setFilters: (field: string, value: string | null) => {
    set((state) => ({
      filters: {
        ...state.filters,
        [field]: value,
      },
    }));
  },
}));


Get plans with filters component

...
  const plansStore = usePlansStore();

  const {
    data,
    refetch: refetchPlans,
    isLoading: isGetPlansLoading,
  } = useGetPlans(plansStore.getFilters());
....


useGetPlans function
export const useGetPlans = (
  filters: PlanFilter
): UseQueryResult<ApiPlanWithPlaces[], unknown> => {
  return useQuery(["plans"], () => getPlans(filters), {
    staleTime: StaleTimeConfigs.TWO_MINUTES,
  });
};


I can think of a solution which is to call refetch() function, or invalidate the query when the filters object changes. But not sure if which one is the better one or a correct way of doing it


Thank you for your help ❤️
Was this page helpful?