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)

Upvotes: 0

Views: 904

Answers (1)

Drew Reese
Drew Reese

Reputation: 203348

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:

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 ... />

Upvotes: 0

Related Questions