0

I think I misunderstand the purpose of RTK Query.

Basically I have an app, where I need to login using email and password, this request returns me userId. That is my API file

export const accountApi = createApi({
reducerPath: 'accountApi',
baseQuery: fetchBaseQuery({ baseUrl: location.origin }),
endpoints: (builder) => {
        getUserId: builder.query({
            query: ({ emailValue, passwordValue }) => ({
                            url: `/users`,
                            headers: {
                              'authentication-failure-code': 403,
                              'Authorization': `Basic btoa(`${(emailValue)}:${(passwordValue)}`)`,
                            }
                            responseHandler: (response) => response.text(),
            })
            transformResponse: (response) => applyDataCallback(response),
        }),
    }
},

On my SignIn page this request returns me userID, which I need to use literally for all future request in my app. But how I can get this id in another component after logging in if I obviously don't have email and password?

export default function MainApp() {
const { data: userId } = useGetUserIdQuery();

useGetUserIdQuery expects such params as login and pass, and of course code like this causes an errors.

useSelector also won't work here, because it gives only not normalized cache.

Am I missing some basics here? Or should I use just simple RTK for saving my id?

tykhan
  • 81
  • 8

1 Answers1

1

Looks like you are mixing up the API layer and storage. RTK-Q brings you a wrapping layer with Cache and other API-related features to make all the data-fetching fetch lifecycle easier and consistent all over the app.

What are you looking for - is a data storage-related question. It can be handled with any of the existing approaches like Redux, Context, Localstorage, etc.

I would say that the most suitable solution for you here - is just to put userId to the localStorage\cookies once after logging in, and after - read it during all the requests in future calls.

To help you with that - you can define a custom queryFunction:

export const customBaseQuery: BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError> 
  = async (args, api, extraOptions = {}) => {
  const userId = localStorage.getItem('userId')
  // Do what you want with userId, and pass it to the request

  const result = await fetchBaseQuery(args, api, extraOptions);

  // Optionally - can handle the response in some way
  return result;
};

After that you can apply it to your api definition, instead of fetchBaseQuery:

baseQuery: customBaseQuery({ baseUrl: location.origin }),
Eugene Tusmenko
  • 836
  • 4
  • 11
  • Yes, you are right. For some reason I thought it could be a replacement for the usual store. – tykhan May 10 '22 at 07:13
  • Actually, at final - it's really reduces what you will store in common redux. After the migration to RTK-Q - i've removed about 90% of stores\actions\reduces defined before, and left only UI-related stuff like page filter selections, some checkboxes values, etc. All the data from API never got copied anywhere to another redux store, no reason for that) So it behaves as "remote" store, with your API\BackEnd under the hood) – Eugene Tusmenko May 10 '22 at 17:41
  • Why do you need to save such values (e.g checkboxes) in redux store? Isn't it supposed to be for some global data that is used all around your app? – tykhan May 11 '22 at 12:21
  • The example is - I have a list in a table, with an option to perform bulk- action over selected rows\items. + Filters for that table And I wanted to persist the state of the filters and selected rows even after leaving the page. So, after navigating back - you'll have the same data in a table, selections and so on. You can move such a state on app root layer, but it feels senseless then you have a Redux already. So I have such a store with filters, selections and so on for each page, where it's necessary. – Eugene Tusmenko May 11 '22 at 15:14