'Get data in component tree using RTK Query

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?



Solution 1:[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 }),

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1