使用RTK查询在组件树中获取数据

发布于 2025-01-26 14:05:55 字数 1153 浏览 1 评论 0原文

我认为我误解了RTK查询的目的。

基本上,我有一个应用程序,需要使用电子邮件和密码登录,此请求将返回我的用户。这是我的

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),
        }),
    }
},

签名页面上的API文件,此请求将返回我的用户ID,我需要在应用程序中的所有将来的请求中使用它。但是,如果我显然没有电子邮件和密码,我如何在登录后将其在另一个组件中获取该ID?

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

USEGETUSERIDQUERY期望登录和通行证等参数,当然代码会导致错误。

USE -Elector也在这里也无法使用,因为它仅提供不归一化的缓存。

我在这里错过了一些基本知识吗?还是我应该只使用简单的RTK来保存我的ID?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绝不放开 2025-02-02 14:05:55

看起来您正在混合API层和存储。
RTK-Q为您带来一个带有缓存和其他与API相关功能的包装层,以使所有数据提取生命周期的所有数据更轻松,一致。

您正在寻找什么 - 是一个与数据存储相关的问题。它可以使用Redux,Context,LocalStorage等任何现有方法来处理。

我要说的是,在这里适合您的解决方案 - 只是在登录后和之后将用户ID放入LocalStorage \ Cookies,然后阅读 - 阅读它在以后的所有请求中。

为了帮助您 - 您可以定义自定义查询功能:

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;
};

之后,您可以将其应用于API定义,而不是fetchbasequery:

baseQuery: customBaseQuery({ baseUrl: location.origin }),

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 }),
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文