I've successfully written my application using Axios to fetch content. As of now, it's set up to fetch content when certain events happen (like the submit button has been clicked.) However, I'm experimenting with Redux's RTK-Query solution. This package generates hooks and in their examples, they provide simple component-level examples that call the hooks on mount.
How can I leverage these rtk-hooks (and hooks in general) so I can tie them to behaviors like onClick
, onSubmit
, and conditional events? I'm aware this conflicts with the rules-of-hooks guidelines, but I can't imagine RTK-Query would be so limited as to only allow component-level onMount API calls.
some related articles I'm reading while I try to figure this out / wait for a helpful example:
- https://blog.logrocket.com/react-hooks-frustrations/
- https://redux-toolkit.js.org/rtk-query/usage/usage-without-react-hooks
The second article seems somewhat relevant but I feel like its beating too far off the path and is making question if it's even worth having rtk-query
installed. I might as well just use axios
since it can be used anywhere in my components and logic. Can someone educate me on how to approach this problem? I'm new to rtk-query, it seems really cool but it also seems really restrictive in its implementation approaches.
Here is an example of my api.ts
slice:
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
const apiEndpoint = 'http://localhost:5000';
export const myApi = createApi({
reducerPath: 'myApi',
baseQuery: fetchBaseQuery({ baseUrl: apiEndpoint }),
endpoints: builder => ({
getFileById: builder.query<any, { id: string; fileId: string }>({
query: arg => {
const { id, fileId } = arg;
return `/service/${id}/files/${fileId}`;
},
}),
}),
});
// RTK Query will automatically generate hooks for each endpoint query
export const { useGetFileByIdQuery } = myApi;
generic example using axios:
const handleSubmit = async (): Promise<void> => {
try {
const getResponse = await axios.get('my-endpoint/abc/123');
}
catch (e) {
...
}
}