简体   繁体   中英

Redux RTK Query - Lazy Query

I simply want to use RTK to run an API request as part of an onSuccess function and await the response. I was doing this in Axios no problem but I'm trying to replace my Axios calls with RTK and having trouble using the LazyQuery.

I'm getting an exception

useLazyQuery is not a function or its return value is not iterable

My API:

const linkAPI = overweightRTK.injectEndpoints({
    tagTypes: ['Link'],
    endpoints: (builder) => ({
        createLink: builder.mutation({
            query: (body) => ({
                url: `/links/`,
                method: 'POST',
                body,
                invalidatesTags: ['Link']
            })
        })
    }),
    overrideExisting: false
});

export const { useCreateLinkMutation} = linkAPI;

My component:

 const [trigger, result, lastPromiseInfo] = OverweightRTK.endpoints.createLink.useLazyQuery()
 const onSuccess = async (data) => {
        const createLinkRequest = { 
               payload: data
        };

        trigger({ createLinkRequest }, { skip: !isSubscriber })
            .unwrap()
            .then(res => {
                if (res.status === 200) {
                    setSuccessMessage('Success, your account linked');
                }
            })
            .catch((error) => console.log(error));
    };

I figured it out. Apparently for mutation endpoints you don't need to use the lazyQuery(). Mutation queries by default return a similar response as lazyQuery and already return the tuple containing the trigger.

Working code: (This replaces the first line in my component code, nothing else needed to be changed)

const [trigger, result, lastPromiseInfo] = useCreateLinkMutation();

Useful docs on the subject: https://redux-toolkit.js.org/rtk-query/usage/mutations

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM