How to trigger data fetching from an action with RTK Query?

I’m not new to Redux, but I am new to RTK and RTK Query. Back in the old days the way you’d trigger data to refetch whenever a specific action happened (I changed my form state, that means I want to fetch new data based on that form state) was you’d dispatch your action, then you’d have a saga that would be listening for that action and kick off a data fetch, which would have its own sequence of actions.

In RTK Query, there’s hooks, which I think are cool. However, I don’t want to have to imperatively trigger data fetching from, say, my form component. I want the store to handle triggering the data fetch by itself completely via actions, and I just want to be able to get the data I need via selectors (or hooks if that’s the proper way with RTKQ).

I have a component that has a set of filters, and I have a component that consumes some data sent back from an API based on those filters. Right now, getting those users is the result of a POST request (the body is the filter state), but I’d like to switch to a get (using query params). I also need the state of the filters in other components, so it needs to be in state.

// what’s currently happening

function FilterFormComponent () {
const [fetchFilteredData, result] = useUpdateFiltersMutation({ fixedCacheKey: "FilteredData" );
  ...
  onFormSubmit(filters) {
    dispatch(updateFilterFormState(filters));
    fetchFilteredData(filters)
  }
}

function DataDisplayComponent() {
  const [, result] = useUpdateFiltersMutation({ fixedCacheKey: "FilteredData"});
  // do something with the data
}

// what I want to happen

function FilterFormComponent () {
  ...
  onFormSubmit(data) {
    dispatch(updateFilterFormState(data))
  }
}

function DataDisplayComponent() {
  const filteredData = useSelector(state => state.filteredData );
  // or
  const [, result] = useUpdateFiltersMutation({ fixedCacheKey: "FilteredData" });

  // do something with the data
}

// somewhere else, middleware?
somewhereElse(state, action) {
  dispatch(api.endpoints.getFilteredData.initiate(action.payload)
}

I don’t know where the “somewhere else” should be. It used to be in a saga, you’d be listening for an action and do your logic there. The point being, I don’t want my form component to have to know anything about fetching the filtered data, its only job should be updating filters state. I want those concerns completely separated, and I don’t want to have to make 2 function calls (dispatch then trigger mutation). Is middleware the correct place to do this in RTK Query?

Also, can I still consume the data caused by the above mutation with hooks? (i.e. in some other component that relies on the data updated by the mutation, can I still use, for example, const [, result] = useUpdateFiltersMutation({ fixedCacheKey: "FilteredData"}) as long as it’s tagged correctly if I dispatch the mutation from, say middleware?

How would I get this to work with a GET request (a query instead of a mutation)? Is there a way to invalidate the tag manually without needing to have a mutation? (the data is only being fetched, not modified so I have no reason to make a mutation, and that would result in 2 http requests anyway)

Also, is RTK Query even a good solution for this use case? I’m tempted to just go and write a thunk so I can make things happen the way I want them to.

EDIT: Edited to make it more clear what I’m trying to accomplish. tl;dr, I want to dispatch an action to update the state of some filters in one component, and have that automatically cause the data to be refetched wherever it is being queried (in some other component using a hook for instance)

New contributor

EibhlìnNicColla is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Assuming your fetchSomeData endpoint is a Query, the solution here is to use query tags and tag invalidation. E.g. the fetchSomeData query endpoint provides some tag(s) and the some mutation endpoint invalidates that/those tag/tags, which triggers the query endpoint to re-run.

See the following for details:

  • Automated Re-fetching
  • createApi providesTags and Providing cache data
  • createApi invalidatesTags and Invalidating cache data

Basic Example:

const api = createApi({
  baseQuery: fetchBaseQuery({
    baseUrl: '/',
  }),
  tagTypes: ['Data'],
  endpoints: (build) => ({
    fetchSomeData: build.query({
      query: () => '/someData',
      providesTags: ['Data'],
    }),
    updateSomeData: build.mutation({
      query: (body) => ({
        url: 'post',
        method: 'POST',
        body,
      }),
      invalidatesTags: ['Data'],
    }),
  }),
})

When the updateSomeData mutation endpoint runs it invalidates the "Data" tag and triggers any endpoints that provide a "Data" tag. The form component only uses the mutation hook and triggers the mutation. The query will be re-triggered and any current subscribers will automatically rerender/receive the updated query endpoint results when they become available.

The only thing I want to do in my form component is dispatch an action
that updates the form state synchronously. That’s it. I don’t want to
trigger the data re-fetch from there. Is there any way for me to
invalidate the tag so that wherever that query is being used, it will
automatically re-fetch, without me needing to use a mutation?

I’m just trying to decouple the filter component from the data
fetching process as much as possible

Yes, you can listen for specific Redux state changes and dispatch an API action to invalidate specific query tags to trigger the query endpoints to re-run. This will look similar to your second snippet attempt.

Example custom hook implementation:

import { useCallback, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { debounce } from "lodash";

import { api } from "./api.slice";

export const useDataListener = (selectorFn, invalidateTags = []) => {
  const dispatch = useDispatch();
  const data = useSelector(selectorFn);

  // Only used to not over-invalidate/trigger the endpoint too often
  const debouncedDispatch = useCallback(debounce(dispatch, 500), [dispatch]);

  useEffect(() => {
    debouncedDispatch(api.util.invalidateTags(invalidateTags));
  }, [data]);
};

Usage: The unit of code is what couples the Redux form state update to the query endpoint you want to trigger/re-trigger. If you don’t want the form component to know anything about the API slice, then I suggest calling the hook one-level up in the component that is also rendering your form component.

useDataListener((state) => state. filteredData, ["Data"]);

...

<Form ... />

9

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật