0

So we're migrating to RTK Query. We've been able to work a query without any problems. But Now we're trying to do a POST, and the following problem happens.

This is my function in my component.tsx file:

const [postToken] = MultiBrandAPI.useNewPartnerTokenPostMutation();

const handleNavigateToPartner = async(partner: Partner) => {

    const auth = SessionSlice.getInitialState().token;
    try {
        const result = await postToken({
            id: partner.id,
            token: auth
        }).unwrap();
        console.log(result);
    } catch (err) {
        console.log(err);
    }
};

And this is my api.ts file:

import {Partner} from '@libs/partner';
import {createApi} from '@reduxjs/toolkit/query/react';

import {BaseQueryWithAuth} from '../redux/rtk-query';

interface PostObject {
    id: string,
    token: string | undefined
}

export default createApi({
    reducerPath: 'multiBrandAPI',
    baseQuery: BaseQueryWithAuth,
    endpoints: (builder) => ({
        newPartnerTokenPost: builder.mutation<string, PostObject>({
            query: ({id, token}: PostObject) => ({
                url: `u/${id}/token`,
                method: 'POST',
                body: `Authorization ${token}`
            }),
            invalidatesTags: [{type: 'Partners', id: 'LIST'}],
        }),
        getAllPartners: builder.query<Partner[], void>({
            query: () => ({url: 'auth/login'}),
            providesTags: () => {
                return [{type: 'Partners'}];
            }
        }),
    }),
    tagTypes: ['Partners']
});

And I'm getting this error on console:

React Hook "MultiBrandAPI.useNewPartnerTokenPostMutation" is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return? react-hooks/rules-of-hooks Blockquote

1 Answers1

0

This has nothing to do with making a POST - you are just violating the rules of hooks.

You have to call useNewPartnerTokenPostMutation in your component function on root level (not in any callbacks) and not inside of if/else blocks and before any possible return statement. The same would go for any other hook in React.

phry
  • 35,762
  • 5
  • 67
  • 81
  • Yes, I realize that from the error message. My question in the post is basicaly: "How do I mage a POST with RKT Query and React" I've been reading the doc and even saw some examples and some examples actually did what I described above with no errors. – TurbaMolesta Apr 11 '22 at 14:18
  • I don't know what else than "you call the method `MultiBrandAPI.useNewPartnerTokenPostMutation` in a wrong spot" I should tell you since you are not showing where you call the method. – phry Apr 11 '22 at 15:22
  • 1
    This was right! calling it before the return was the trick! Tks for your help! – TurbaMolesta Apr 12 '22 at 15:07