How to cancel the RTK-Query requests #4489
DavidNguyen67
started this conversation in
General
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I want to proactively abort a query in a React component when necessary. At the same time, I want to use useEffect to ensure that the query will be canceled when the component is unmounted.
userApi.slice.ts
`export const userApi = createApi({
baseQuery: axiosBaseQuery(),
tagTypes: [QUERY_TAG.USER, QUERY_TAG.COUNT_USER],
endpoints: (build) => ({
getUsers: build.query<UserEntity[] | null, ListUserDto>({
queryFn: async (payload, _queryApi, extraOptions, baseQuery) => {
try {
const data = await userService.listUsers(payload, {});
return { data };
} catch (error) {
return { error };
}
},
providesTags: (result, error, arg) =>
result && result?.length > 0
? [
...result.map(({ id }) => ({
type: QUERY_TAG.USER as const,
id,
})),
QUERY_TAG.USER,
]
: [QUERY_TAG.USER],
}),
countUsers: build.query<number | null, undefined>({
queryFn: async (, _queryApi, _extraOptions, baseQuery) => {
try {
const data = await userService.countUser({});
return { data };
} catch (error) {
return { error };
}
},
providesTags: (result, error, arg) => [QUERY_TAG.COUNT_USER],
}),
registerUses: build.mutation<string | null, CreateUserDto>({
queryFn: async (payload, _queryApi, _extraOptions, baseQuery) => {
const { signal } = _queryApi;
}),
});`
Component.tsx
`let promise: any;
const Home = () => {
const { data } = useGetUsersQuery({
offset: 0,
limit: 30,
});
const { data: count } = useCountUsersQuery(undefined, {
pollingInterval: API_TIME_POLLING,
});
// Define the columns for the table
const columns: TableProps['columns'] = useMemo(
() => [
{
title: '#',
dataIndex: 'index',
render: (text, record, index) => index + 1,
width: 15, // Thiết lập chiều rộng cho cột số thứ tự
align: 'center',
fixed: 'left',
},
{
title: 'Email',
dataIndex: 'email',
width: 200, // Thiết lập chiều rộng cho cột email
},
{
title: 'Name',
dataIndex: 'name',
render: (text, record) =>
${record.firstName} ${record.lastName}
,width: 150, // Thiết lập chiều rộng cho cột tên
},
],
[]
);
const [addUser, { isLoading, error }] = useRegisterUsesMutation();
const handleGenerateAnUser = useCallback(async () => {
try {
const payload: CreateUserDto = {
email: faker.internet.email(),
firstName: faker.person.firstName(),
id: faker.string.uuid(),
lastName: faker.person.lastName(),
};
}, [addUser]);
const handleAbortQuery = useCallback(() => {
promise.abort();
promise = null;
}, []);
useEffect(() => {
return () => {
if (promise) {
promise.abort();
promise = null;
}
};
}, []);
return (
<>
<Button
type='primary'
onClick={handleGenerateAnUser}
// loading={isLoading}
>
Generate a user
Abort query
{data && data?.length > 0 && (
<>
<Table
columns={columns}
dataSource={data}
rowKey={'id'}
loading={isLoading}
size='small'
sticky
// pagination={{
// defaultPageSize: 5,
// pageSizeOptions: [10, 20, 50, 100],
// }}
bordered
/>
</>
)}
</>
);
};
export default Home;`
Beta Was this translation helpful? Give feedback.
All reactions